如何判断MongoDB中的查询是否还有更多结果? [英] How can I tell if there are more results from a query in MongoDB?

查看:124
本文介绍了如何判断MongoDB中的查询是否还有更多结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种优选的方法来查询带限制的mongo并知道如果我用跳过/限制查询下一页是否还会有更多结果?

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.

推荐答案

MongoDB具有可定位游标,它使您可以在返回所有数据之后重用游标.看起来像这样:

MongoDB has tailable cursors, which allow you to reuse a cursor after all data has been returned. It would look something like this:

n = 10
docs = db.documents.find({"foo": "bar"}).limit(n)
more = docs.hasNext()

请注意,仅检索了10个文档,但是可以检查光标以确定是否有更多可用的对象.唯一的问题是可尾游标只能用于加盖的集合.

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.

以上内容也可以与常规光标一起使用,但是您必须查询n + 1文档.这基本上与您现在使用的解决方案相同.不过,您必须使用size(),因为这会考虑到skip和limit修饰符.

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 use size() though, as that takes the skip and limit modifiers into account.

n = 10
docs = db.documents.find({"foo": "bar"}).limit(n + 1)
more = db.size() > n

我对PyMongo并不熟悉,所以我不确定这一点,但是这种解决方案可能会将n + 1完整文档发送到您的应用程序,而不是所需的n,从而导致带宽较小高架.如果是这种情况,您可能想创建一个服务器端函数,该函数执行相同的操作,但是仅返回一个对象,该对象在数组中包含n个文档,以及一个标志,该标志指示是否n + 1 th 文档可用.

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 required n, 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 containing n documents in an array, and a flag that indicates if an n + 1th document is available.

这篇关于如何判断MongoDB中的查询是否还有更多结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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