如何判断 MongoDB 中的查询是否有更多结果?
是否有一种首选方法可以用限制查询 mongo,并知道如果我用skip/limit 查询下一页是否会有更多结果?
我一直在做的是请求比我需要的多一份文档,将其从末尾切掉,并利用该额外文档的存在来了解另一个查询是否会给出至少一个结果。
n = 10
docs = db.documents.find({'foo': 'bar'}).limit(n+1)
more = docs.count() > n
docs = docs[:n]
我觉得这是一个常见的用例(知道是否在网站上显示“更多结果”按钮),并且我对当前的解决方案感到愚蠢。
Is there a preferred way to query mongo with a limit and know whether there will be more results if I query for the next page with skip/limit?
What I have been doing is asking for one more document than I need, slicing it off the end, and using the existence of that extra document to know whether another query will give at least one more result.
n = 10
docs = db.documents.find({'foo': 'bar'}).limit(n+1)
more = docs.count() > n
docs = docs[:n]
I feel like this is a common use case (knowing whether or not to show an "more results" button on a website) and I feel stupid with my current solution.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
MongoDB 有 tailable 游标,它允许您在所有数据都被删除后重用游标回来了。它看起来像这样:
请注意,仅检索到 10 个文档,但可以检查光标以确定是否有更多可用对象。唯一的问题是可尾游标只能用于上限集合。
上面的内容也可以与常规游标一起使用,但您必须查询
n + 1
文档。这基本上与您现在使用的解决方案相同。不过,您必须使用size()
,因为这会考虑到skip 和 limit 修饰符。我对 PyMongo 不熟悉,所以我不确定这一点,但该解决方案有可能将
n + 1
完整文档发送到您的应用程序,而不是所需的n
,导致较小的带宽开销。如果是这种情况,您可能希望创建一个执行相同操作的服务器端函数,但仅返回一个包含数组中的n
文档的对象,以及一个指示是否n + 第 1 个
文档可用。MongoDB has tailable cursors, which allow you to reuse a cursor after all data has been returned. It would look something like this:
Note that there are only 10 documents retrieved, but the cursor can be inspected to determine if there are more objects available. The only problem is that tailable cursors can only be used on capped collections.
The above can also be used with a regular cursor, but you'd have to query for
n + 1
documents. This is basically the same solution as you're using now. You have to usesize()
though, as that takes the skip and limit modifiers into account.I'm not familiar with PyMongo, so I don't know this for sure, but there's a possibility that this solution sends
n + 1
full documents to your application, rather than the requiredn
, resulting in minor bandwidth overhead. If that's the case, you may want to create a server-side function that does the same, but only returns an object containingn
documents in an array, and a flag that indicates if ann + 1
th document is available.