mongodb - 如何在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”时间查询文档。
解决方案
就这么简单:
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}} )
推荐阅读
- regex - 使用 Perl 的 RegEx 查找集合的任何排列
- python - pyautogui 不会从 csv 的列表中输入
- c++ - 是否允许在作为静态数据结构成员的 lambda 函数中捕获变量?
- spring - Spring Cloud Function AWS 示例无法在本地运行
- python - 如何有效地搜索旧/旧 TensorFlow 文档?
- python - np.dot 在乘法矩阵中的结果问题
- laravel - 从 ajax 请求中保存 laravel_session cookie - 单点登录
- python-3.x - Python打印对齐的numpy数组
- macos - 具有 AutoLayout 约束的 NSScrollView 使窗口对调整大小和拖动无响应
- python-3.x - 尝试编译 python3 kivy 应用程序时出错