使用限制时使用 MongoDB 获取文档总数 [英] Get a count of total documents with MongoDB when using limit

查看:25
本文介绍了使用限制时使用 MongoDB 获取文档总数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对优化我正在使用 MongoDB 的分页"解决方案感兴趣.我的问题很直接.我通常使用 limit() 功能来限制返回的文档数量.这迫使我在没有 limit() 函数的情况下发出冗余查询,以便我也捕获查询中的文档总数,以便我可以将其传递给客户端,让他们知道他们将不得不发出额外的请求以检索其余文档.

I am interested in optimizing a "pagination" solution I'm working on with MongoDB. My problem is straight forward. I usually limit the number of documents returned using the limit() functionality. This forces me to issue a redundant query without the limit() function in order for me to also capture the total number of documents in the query so I can pass to that to the client letting them know they'll have to issue an additional request(s) to retrieve the rest of the documents.

有没有办法将其压缩为 1 个查询?获取文档总数但同时仅使用 limit() 检索子集?考虑这个问题的方式与我处理它的方式不同吗?

Is there a way to condense this into 1 query? Get the total number of documents but at the same time only retrieve a subset using limit()? Is there a different way to think about this problem than I am approaching it?

推荐答案

不行,别无他法.两个查询 - 一个用于计数 - 一个带有限制.或者您必须使用不同的数据库.例如,Apache Solr 可以像您想要的那样工作.每个查询都有限制返回totalCount.

No, there is no other way. Two queries - one for count - one with limit. Or you have to use a different database. Apache Solr for instance works like you want. Every query there is limited and returns totalCount.

这篇关于使用限制时使用 MongoDB 获取文档总数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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