首页 > 解决方案 > 如何在mongodb中的一个查询中查询在给定文档之后插入的所有文档?

问题描述

假设我有这些文档:

{ "_id" : ObjectId("50911c3e09913b2c643f1215"), "name" : "x", "time" : 1617131149850 }
{ "_id" : ObjectId("50911c4709913b2c643f1216"), "name" : "y", "time" : 1617131149851 }
{ "_id" : ObjectId("50911c4b09913b2c643f1217"), "name" : "w", "time" : 1617131149852 }
{ "_id" : ObjectId("50911c4f09913b2c643f1218"), "name" : "q", "time" : 1617131149853 }
{ "_id" : ObjectId("50911c6309913b2c643f1219"), "name" : "z", "time" : 1617131149854 }

我想获取时间大于文档时间的所有文档_id="50911c4b09913b2c643f1217"(导致“q”和“z”)。

我怎样才能只用一个查询而不是两个或更多查询结果?

例如,我不想在单独的查询中获取“w”,然后在另一个查询中根据“w”时间查询文档。

标签: mongodb

解决方案


就这么简单:

db.collection.find({
  _id: {
    $gt: ObjectId("50911c4b09913b2c643f1217")
  }
})

根据您的评论,一种解决方案是:

db.collection.aggregate([
  { $group: { _id: null,  data: { $push: "$$ROOT" } } },
  {
    $set: {
      filter: {
        $first: {
          $filter: {
            input: "$data",
            cond: { $eq: [ "$$this._id", ObjectId("50911c4b09913b2c643f1217") ] }
          }
        }
      }
    }
  },
  {
    $project: {
      data: {
        $filter: {
          input: "$data",
          cond: { $gt: [ "$$this.time", "$filter.time" ] }
        }
      }
    }
  },
  { $unwind: "$data" },
  { $replaceRoot: { newRoot: "$data" } }
])

但是,如果您使用的是 mongoshell,即 JavaScript,我会简单地这样做:

var t = db.collection.findOne( {_id: ObjectId("50911c4b09913b2c643f1217")} ).time
db.collection.find( {time: {$gt: t}} )

推荐阅读