Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB count() versus countDocuments()

I am using MongoDB and more specifically Mongoose. I've recently been getting rid of some deprecation warnings from updating mongo and mongoose.

Some of my queries might as shown:

const count = await Badge.find(query).count().exec()

I have since changed this to

const count = Badge.find(query).countDocuments().exec()

and viola the depracation warning is gone. However, reading the documentation at MongoDB it seems that it should be written like this:

const count = Badge.countDocuments(query)

All of the above return the exact same thing. Obviously the latter two are the ones I want because of the depracation of count().

What is the difference between the second two and should I prefer one over the other?

like image 879
SKeney Avatar asked Dec 31 '22 18:12

SKeney


1 Answers

The db.collection.find method returns a cursor. The cursor.count() method on the cursor counts the number of documents referenced by a cursor. This is same as the db.collection.count().

Both these methods (the cursor.count() and db.collection.count()) are deprecated as of MongoDB v4.0. From the documentation:

MongoDB drivers compatible with the 4.0 features deprecate their respective cursor and collection count() APIs in favor of new APIs for countDocuments() and estimatedDocumentCount(). For the specific API names for a given driver, see the driver documentation.

Avoid using the db.collection.count() method without a query predicate since without the query predicate, the method returns results based on the collection’s metadata, which may result in an approximate count.

db.collection.countDocuments(query) returns the count of documents that match the query for a collection or view. This is the method you need to use to count the number of documents in your collection.

All of the above return the exact same thing.

Yes, most of the times. Only, the countDocuments returns the actual count of the documents. The other methods return counts based upon the collection's meta data.

If you want to use db.collection.count, use it with a query predicate, and this will return the exact count of the documents (but, note that this method is deprecated).

like image 93
prasad_ Avatar answered Jan 06 '23 12:01

prasad_