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

- 143,130
- 81
- 406
- 459

- 1,132
- 1
- 7
- 12
3 Answers
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.

- 143,130
- 81
- 406
- 459

- 25,180
- 8
- 56
- 83
-
Both seems to be same...Still why have they introduced 2 such methods?is there any performance difference between the two? – Byter Aug 09 '12 at 10:31
-
They are not same. One takes limit/skip into consideration but other not. – Parvin Gasimzade Aug 09 '12 at 10:38
-
13I suspect the difference is in the `does not take` and the `does take` limit/skip into consideration. – Peter Lawrey Aug 09 '12 at 10:38
-
1@RemonvanVliet Sometimes subtly is lost when you feel overloaded with information. ;) – Peter Lawrey Aug 09 '12 at 12:37
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.

- 1
- 1

- 56
- 3
-
Are you saying that the `cursor.count()` not only ignored the limit as documented, but actually removed the limit from the cursor, such the subsequent operations such as iterating the cursor behave as if the limit was not set? – dan carter Jun 16 '16 at 23:15
When I first read the documentation on the difference between cursor.count
and cursor.size
, I was similarly stumped b/c I didn't understand what it meant to not consider skip
or limit
. I found this article to be helpful read more here. I think the following example illustrates the differences
// 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();
5

- 501
- 5
- 8