使用限制时使用 MongoDB 获取总文档数 [英] Get a count of total documents with MongoDB when using limit
问题描述
我有兴趣优化我正在使用 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屋!