最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

按特定顺序查找mongodb

网站源码admin31浏览0评论

按特定顺序查找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)

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论