MongoDB的DBCursor的cursor.count()方法和cursor.size()方法有什么不同
发布于 2012-08-09 18:29:44
从Javadoc of the MongoDB Java Driver上看,它说:
DBCursor.count():统计与查询匹配的对象的数量。这不会使 limit/skip考虑在内。
DBCursor.size():统计与查询匹配的对象的数量。这确实考虑到了限制/跳过。
发布于 2015-10-31 13:16:21
除了回答之外,我还想指出一个问题,我们的团队面临着“混合”这两个问题。
我们有类似这样的东西:
DBCursor cursor = collection.find(query).limit(batchSize);
logger.info("{} items found.", cursor.count());
while (cursor.hasNext()) {
...
}原来,在调用cursor.count()方法之后,限制是忽略了(请看一下其他问题),我们想知道查询返回了多少项,所以我们应该调用cursor.size()方法,因为调用count one确实有一个不希望的附带效果。
我希望这能对其他人有所帮助,因为要找到我们面临的问题的根源并不容易。
发布于 2021-08-13 23:20:25
当我第一次阅读关于cursor.count和cursor.size之间区别的文档时,我同样被难住了,我不明白不考虑skip或limit意味着什么。我发现这篇文章对read more here很有帮助。我认为下面的例子说明了其中的区别。
// by default cursor.count ignores limit or skip. note that 100 records were returned despite the limit being 5
> db.restaurants.find( { "cuisine": "Bakery", "address.zipcode": "10462" } ).limit(5).count();
100
// if you want to consider limits and skips, then add an optional parameter specifying so
> db.restaurants.find( { "cuisine": "Bakery", "address.zipcode": "10462" } ).limit(5).count(true);
5
// cursor.size on the other hand abides by limits and skips
> db.restaurants.find( { "cuisine": "Bakery", "address.zipcode": "10462" } ).limit(5).size();
5https://stackoverflow.com/questions/11881347
复制相似问题