Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Count number of rows in a MongoDB collection
To count the number of documents in a MongoDB collection, use the countDocuments() method. This method returns the total number of documents that match the specified query criteria.
Syntax
db.collection.countDocuments(query, options)
Where query is optional. If omitted, it counts all documents in the collection.
Sample Data
Let us create a collection with sample documents ?
db.demo664.insertMany([
{_id: 1, ClientName: "Chris"},
{_id: 2, ClientName: "Bob"},
{_id: 3, ClientName: "Sam"},
{_id: 4, ClientName: "David"}
]);
{
"acknowledged": true,
"insertedIds": [1, 2, 3, 4]
}
Display all documents from the collection ?
db.demo664.find();
{ "_id": 1, "ClientName": "Chris" }
{ "_id": 2, "ClientName": "Bob" }
{ "_id": 3, "ClientName": "Sam" }
{ "_id": 4, "ClientName": "David" }
Example: Count All Documents
Count the total number of documents in the collection ?
db.demo664.countDocuments();
4
Example: Count with Query Filter
Count documents that match specific criteria ?
db.demo664.countDocuments({ClientName: "Chris"});
1
Alternative Methods
You can also use estimatedDocumentCount() for faster approximate counts on large collections ?
db.demo664.estimatedDocumentCount();
4
Key Points
- countDocuments() − Accurate count, supports query filters
- estimatedDocumentCount() − Faster but approximate count for entire collection
- The deprecated
count()method should be avoided in favor ofcountDocuments()
Conclusion
Use countDocuments() to get accurate document counts in MongoDB collections. It supports query filters and is the recommended method for counting documents with specific criteria.
