Count documents satisfying a query in MongoDB Collection (countDocuments, $regex, $in)

In this lesson, we learn that counting documents that meet certain criteria in MongoDB can be done with the countDocuments() method.

We demonstrate how to retrieve the total number of documents when no query is specified and how to filter results using regular expressions.

For example, we can count employees with names containing a lowercase "a" or those with specific skills, using $regex.

Additionally, we show how to count documents where age is not equal to a given value, illustrating the versatility of the countDocuments() method in various scenarios.

Share with a coworker

Transcript

[00:00] In order to count the number of documents that satisfy a given criteria in Mongo, we can use the collection.countDocuments() as we've seen before. Now if we run it without any query, it's going to return the total number of all documents. But we can go back to the find queries that we've been using before and let's say that we have employees find so that means find multiple documents that have name and within the name let's say that there would be a regex that has a so anyone who has the a lowercase letter is going to be returned over here so what we can do is basically to replace the find method with count documents and essentially count documents and find accept the query parameter as the first parameter of this method the same way. Everything that we've seen before is going to be supported over here. So let's also take this example, employees find, and we're going to check whether any of the documents being filtered has at least one of these skills again count documents everything is going to be correct as long as I don't make any typos so there is five.

[01:17] Let's also take one more so the query that we've had is let's say that the age is going to be not equal to 30 so we had some results over here and let's replace it with count documents and we have 12.