Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 730
Byter Avatar asked Aug 09 '12 10:08

Byter


People also ask

Why do we need cursor in MongoDB?

The Cursor is a MongoDB Collection of the document which is returned upon the find method execution. By default, it is automatically executed as a loop. However, we can explicitly get specific index document from being returned cursor. It is just like a pointer which is pointing upon a specific index value.

Do I need to close MongoDB cursor?

Cursors are automatically closed by the mongo server when they're inactive for more than 10 minutes, or if the client has exhausted the cursor. The MongoDB docs recommend either closing cursors, or ensuring they're exhausted by the client.


2 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.

like image 53
Parvin Gasimzade Avatar answered Oct 20 '22 03:10

Parvin Gasimzade


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.

like image 23
David Chaverri Avatar answered Oct 20 '22 02:10

David Chaverri