使用限制时使用 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屋!