MongoDB replacement cursor.count on type collection.countDocuments

Hello there!

I see that cursor.count is deprecated.
However, I cannot seem to find what can replace it when we are using it with the type ‘FindCursor<WithId>’.
In other words, collection.estimatedDocumentCount and collection.countDocuments is not usable in this context.

I am trying to get the count of documents from a collection with a specific sort and query (find):

	let totalJobs = 0;

	totalJobs = await mongoDb
		.collection("jobs")
		.find(query)
		.sort({ publicationDate: -1 })
		.countDocuments();

What should I used isntead of .count() /.countDocuments();?

Thanks in advanced!

Hi @Marving_Moreton,
You can use this way to perform the same operation:

db.collection.aggregate([
   { $match: <query> },
   { $group: { _id: null, n: { $sum: 1 } } }
])

As mentioned in the documentation.

Hoping It help you!

Regards

1 Like

I really do not understand by the above and why it could matter when counting documents.

I really do not understand why you are sorting when counting documents. It could potentially be slow for no added benefits. The count will be the same with or without sorting.

You may call countDocuments with the query. So your statement should be

2 Likes

Hello,

Correct. Apologies, still very junior here!

I have refactored my db calls and has not realized that I did not require to sort for the count :smile:

Thanks for your help guys!

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.