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?

Solution 1

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 collections 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).

Solution 2

db.collection.count() does not count the actual number of documents, it returns results based on the collections metadata, which may result in an approximate count.

See db.collection.count()

For proper distinction MonogDB introduced countDocuments() and estimatedDocumentCount() methods.

Solution 3

What I remember the count() method was used for mongo shell. and if you want to implement this on nodejs you must use the countDocuments() based on the nodejs driver.

also, according to mongodb documentation db.collection.count()

Returns the count of documents that would match a find() query for the collection or view. The db.collection.count() method does not perform the find() operation but instead counts and returns the number of results that match a query.

Link about db.collection.count()