如何判断 MongoDB 中的查询是否有更多结果?

发布于 2024-09-15 12:34:13 字数 316 浏览 1 评论 0原文

是否有一种首选方法可以用限制查询 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

无名指的心愿 2024-09-22 12:34:14

MongoDB 有 tailable 游标,它允许您在所有数据都被删除后重用游标回来了。它看起来像这样:

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

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

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

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

我对 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:

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

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 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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文