如果这是我的收藏结构:
{ _id: ObjectId("4fdbaf608b446b0477000142"), name: "product 1" }
{ _id: ObjectId("4fdbaf608b446b0477000143"), name: "product 2" }
{ _id: ObjectId("4fdbaf608b446b0477000144"), name: "product 3" }
我查询产品 1,有没有办法查询下一个文档,在这种情况下是“产品 2”?
如果这是我的收藏结构:
{ _id: ObjectId("4fdbaf608b446b0477000142"), name: "product 1" }
{ _id: ObjectId("4fdbaf608b446b0477000143"), name: "product 2" }
{ _id: ObjectId("4fdbaf608b446b0477000144"), name: "product 3" }
我查询产品 1,有没有办法查询下一个文档,在这种情况下是“产品 2”?
sort()
如果您想要一个可预测的结果顺序,最好添加明确的标准。
假设您的顺序是“插入顺序”并且您使用的是 MongoDB 默认生成的 ObjectId,那么您可以根据 ObjectId 进行查询:
// Find next product created
db.products.find({_id: {$gt: ObjectId("4fdbaf608b446b0477000142") }}).limit(1)
请注意,此示例仅有效,因为:
_id
将使用默认_id
索引(按 id 排序)来查找匹配项所以实际上,这种隐式排序与以下内容相同:
db.products.find({_id: {$gt: ObjectId("4fdbaf608b446b0477000142" )}}).sort({_id:1}).limit(1);
如果您向查询添加了更多条件以限定如何查找“下一个”产品(例如 a category
),则查询可能使用不同的索引,并且顺序可能与您预期的不同。
您可以使用explain()检查索引使用情况。
您可以使用 ObjectId 按插入顺序取回项目。见:http ://www.mongodb.org/display/DOCS/Optimizing+Object+IDs#OptimizingObjectIDs
如果您想以其他顺序取回它们,那么您将必须定义该顺序是什么并将更多信息存储在您的文档中。
Starting in Mongo 5
, it's a perfect use case for the new $setWindowFields
aggregation operator:
// { _id: 1, name: "product 1" }
// { _id: 2, name: "product 2" }
// { _id: 3, name: "product 3" }
db.collection.aggregate([
{ $setWindowFields: {
sortBy: { _id: 1 },
output: { next: { $push: "$$ROOT", window: { documents: [1, 1] } } }
}}
])
// { _id: 1, name: "product 1", next: [{ _id: 2, name: "product 2" }] }
// { _id: 2, name: "product 2", next: [{ _id: 3, name: "product 3" }] }
// { _id: 3, name: "product 3", next: [ ] }
This:
$sort
s documents by their order of insertion using their _id
s (ObjectId
s contain the timestamp of insertion): sortBy: { _id: 1 }
next
field in each document (output: { running: { ... }}
)
$push
ing the whole document $$ROOT
($push: "$$ROOT"
)window
) which is in this case is a range of only the next document document: window: { documents: [1, 1] }
.