按特定顺序查找mongodb

编程入门 行业动态 更新时间:2024-10-03 17:17:07

按特定<a href=https://www.elefans.com/category/jswz/34/1771364.html style=顺序查找mongodb"/>

按特定顺序查找mongodb

 [
  { position: 1, slot: 1 ,status: false},
  { position: 2, slot: 2,status:false},
  { position: 3, slot: 3,status:false},
  { position: 4, slot: 4,status:false},
  { position: 5, slot: 5,status:true},
  { position: 6, slot:6,status:true},
  { position: 7, slot: 7,status:false},
  { position: 8, slot: 8,status:false},
  { position: 9, slot: 9,status:false},
  { position: 10, slot: 10,status:false},
  { position: 11, slot: 11,status:false},
  { position: 12, slot: 12,status:false},
  { position: 13, slot: 13,status:false},
  { position: 14, slot: 14,status:false},
  { position: 15, slot:15,status:false},
  { position: 16, slot:16,status:false},
  { position: 17, slot: 17,status:false},
  { position: 18, slot: 18,status:false},
  { position: 19, slot: 19,status:true},
  { position: 20, slot: 20,status:true},

]

查找文档从 slot 6 开始,文档状态为 true。 incase slot 6 to 20 false slot 5 将被返回

注意:查找顺序应该是 6,7,8,..20,1,2,3,4,5

{ position: 6, slot:6,status:true}
回答如下:

我们可以在查询中使用

$elemMatch
运算符来查找下一个条目状态为 false 的第一个元素。

db.collection.find({ 
  $and: [
    { status: true }, 
    { $where: "this.position + 1 < this.length" }, 
    { $expr: { $eq: [ false, { $arrayElemAt: [ "$status", { $add: [ "$position", 1 ] } ] } ] } }
  ] 
}).sort({ position: 1 }).limit(1)

更多推荐

按特定顺序查找mongodb

本文发布于:2024-05-30 13:50:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1770564.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:顺序   mongodb

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!