Difference between cursor.count() and cursor.size(

2019-02-11 20:49发布

What is the difference between the cursor.count() and cursor.size() methods of MongoDB's DBCursor?

2条回答
唯我独甜
2楼-- · 2019-02-11 21:32

From the Javadoc of the MongoDB Java Driver, it says :

DBCursor.count(): Counts the number of objects matching the query. This does not take limit/skip into consideration.

DBCursor.size(): Counts the number of objects matching the query. This does take limit/skip into consideration.

查看更多
女痞
3楼-- · 2019-02-11 21:39

More than an answer I'd like to point out an issue that our team faced "mixing" this two.

We had something like this:

DBCursor cursor = collection.find(query).limit(batchSize);

logger.info("{} items found.", cursor.count());

while (cursor.hasNext()) {
...
}

It turned out that after calling the cursor.count() method, the limit was ignored (plase take a look at this other question) , we intended to know how many items were returned by the query so we should have called the cursor.size() method instead, since calling the count one did have an undesired collateral effect.

I hope this could be helpful to anyone else since it was not that easy to find the source of the issue we were facing.

查看更多
登录 后发表回答