如何在mongodb中的一个查询中查询在给定文档之后插入的所有文档? [英] How to query all documents inserted after a given doc in just One query in mongodb?

查看:44
本文介绍了如何在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").

I want to get all documents with time greater than time of the document with _id="50911c4b09913b2c643f1217" (which results to "q" and "z").

如何只用一个查询而不是两个或多个查询来获得结果?

How can I make the result with just One query not two or more?

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

for example I don't want to fetch "w" in a separate query and then query for docs based on "w" time in another query.

推荐答案

就这么简单:

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

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

Based on your comment one solution is this one:

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,我会简单地这样做:

However, if you are in mongoshell, i.e. JavaScript I would simply do this:

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

这篇关于如何在mongodb中的一个查询中查询在给定文档之后插入的所有文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆