mongodb获取计数,不重复find [英] mongodb get count without repeating find
问题描述
在MongoDb中执行查询时,我需要获取所有匹配的总数,以及文档本身作为有限/分页子集。
When performing a query in MongoDb, I need to obtain a total count of all matches, along with the documents themselves as a limited/paged subset.
我可以实现两个查询的目标,但我不知道如何使用一个查询。我希望有一个mongo功能,在某种意义上,等同于SQL_CALC_FOUND_ROWS,因为它似乎overkill必须运行查询两次。任何帮助将是伟大的。谢谢!
I can achieve the goal with two queries, but I do not see how to do this with one query. I am hoping there is a mongo feature that is, in some sense, equivalent to SQL_CALC_FOUND_ROWS, as it seems like overkill to have to run the query twice. Any help would be great. Thanks!
编辑:以下是执行上述操作的Java代码。
Here is Java code to do the above.
DBCursor cursor = collection.find(searchQuery).limit(10);
System.out.println("total objects = " + cursor.count());
推荐答案
我不知道您使用的是哪种语言,但是通常可以在 find
查询的结果的游标上调用 count
方法,然后使用光标以获取文档本身。
I'm not sure which language you're using, but you can typically call a count
method on the cursor that's the result of a find
query and then use that same cursor to obtain the documents themselves.
这篇关于mongodb获取计数,不重复find的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!