返回 MongoDB 中围绕 ID 的文档范围 [英] Return range of documents around ID in MongoDB

查看:18
本文介绍了返回 MongoDB 中围绕 ID 的文档范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文档的ID,需要返回文档加上前面的10个文档和后面的10个文档.总共 21 个文档.

I have an ID of a document and need to return the document plus the 10 documents that come before and the 10 documents after it. 21 docs total.

我没有任何键的开始或结束值.只有任一方向的限制.

I do not have a start or end value from any key. Only the limit in either direction.

最好的方法是什么?提前致谢.

Best way to do this? Thank you in advance.

推荐答案

您是否知道 ObjectID's 包含时间戳?因此它们总是代表自然的插入顺序.因此,如果您要在已知文档 _id 之前查找文档,您可以这样做:

Did you know that ObjectID's contain a timestamp? And that therefore they always represent the natural insertion order. So if you are looking for documents before an after a known document _id you can do this:

我们的文件:

{ "_id" : ObjectId("5307f2d80f936e03d1a1d1c8"), "a" : 1 }
{ "_id" : ObjectId("5307f2db0f936e03d1a1d1c9"), "b" : 1 }
{ "_id" : ObjectId("5307f2de0f936e03d1a1d1ca"), "c" : 1 }
{ "_id" : ObjectId("5307f2e20f936e03d1a1d1cb"), "d" : 1 }
{ "_id" : ObjectId("5307f2e50f936e03d1a1d1cc"), "e" : 1 }
{ "_id" : ObjectId("5307f2e90f936e03d1a1d1cd"), "f" : 1 }
{ "_id" : ObjectId("5307f2ec0f936e03d1a1d1ce"), "g" : 1 }
{ "_id" : ObjectId("5307f2ee0f936e03d1a1d1cf"), "h" : 1 }
{ "_id" : ObjectId("5307f2f10f936e03d1a1d1d0"), "i" : 1 }
{ "_id" : ObjectId("5307f2f50f936e03d1a1d1d1"), "j" : 1 }
{ "_id" : ObjectId("5307f3020f936e03d1a1d1d2"), "j" : 1 }

所以我们知道f"的_id,得到它和接下来的2个文档:

So we know the _id of "f", get it and the next 2 documents:

> db.items.find({ _id: {$gte: ObjectId("5307f2e90f936e03d1a1d1cd") } }).limit(3)

{ "_id" : ObjectId("5307f2e90f936e03d1a1d1cd"), "f" : 1 }
{ "_id" : ObjectId("5307f2ec0f936e03d1a1d1ce"), "g" : 1 }
{ "_id" : ObjectId("5307f2ee0f936e03d1a1d1cf"), "h" : 1 }

反过来做同样的事情:

> db.items.find({ _id: {$lte: ObjectId("5307f2e90f936e03d1a1d1cd") } })
    .sort({ _id: -1 }).limit(3)
{ "_id" : ObjectId("5307f2e90f936e03d1a1d1cd"), "f" : 1 }
{ "_id" : ObjectId("5307f2e50f936e03d1a1d1cc"), "e" : 1 }
{ "_id" : ObjectId("5307f2e20f936e03d1a1d1cb"), "d" : 1 }

这是一种比扫描集合更好的方法.

And that's a much better approach than scanning a collection.

这篇关于返回 MongoDB 中围绕 ID 的文档范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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