Video Transcript (English)
Greetings! In this video, we’ll learn how to count the number of documents matching a query.
We count documents in MongoDB using the `countDocuments()` collection method.
The syntax for countDocuments() is db.collection.countDocuments().
The method takes a query parameter, which selects the documents to be counted.
Let’s see countDocuments() in action.
We’ll start with a basic example, counting all documents in a collection. Later we’ll count documents with a more complex query.
We’re working with a database called `training` and querying its `trips` collection.
This collection contains data on trips using a bike rental service.
Let’s run a `findOne()` command to see a sample document.
This document contains data on one trip made using a rental bike, including the trip duration, start and end stations, and user information.
We run this operation with `db.trips.countDocuments()`.
To count the number of documents in the `trips` collection, we use `countDocuments()` with an empty document in the query parameter. The empty document signifies the full collection.
Let’s run the operation. There are a total of 10,000 documents in this collection.
Let’s see a more complex example.
Say we want to count the number of trips over 120 minutes long made by subscribers to the bike rental service .
We’re using the countDocuments collection method again. This time in the query parameter we enter a query matching documents where the trip duration is over 120 minutes and the usertype is "Subscriber".
Let’s run the operation. We have a count returned of 7,847 trips!
Let’s recap what we learned in this video. We saw how to count the number of documents returned from a query using `db.collection.countDocuments`.
countDocuments() takes a query parameter. While we’ve used basic queries in our example, you can include any query in your query parameter.
Congratulations! You now know how to count documents matching a query with MongoDB!