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
Selected Reading
How to count the number of documents in a MongoDB collection?
To count the number of documents in a MongoDB collection, use the countDocuments() method or the legacy count() method. The countDocuments() method is recommended for accurate results.
Syntax
db.collectionName.countDocuments();
db.collectionName.countDocuments({query});
Create Sample Data
Let us first create a collection with documents ?
db.countNumberOfDocumentsDemo.insertMany([
{"CustomerName": "Bob"},
{"CustomerName": "Ramit", "CustomerAge": 23},
{"CustomerName": "Adam", "CustomerAge": 27, "CustomerCountryName": "US"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c9a5e2015e86fd1496b38a1"),
ObjectId("5c9a5e3515e86fd1496b38a2"),
ObjectId("5c9a5e4c15e86fd1496b38a3")
]
}
Display all documents from the collection ?
db.countNumberOfDocumentsDemo.find().pretty();
{ "_id": ObjectId("5c9a5e2015e86fd1496b38a1"), "CustomerName": "Bob" }
{
"_id": ObjectId("5c9a5e3515e86fd1496b38a2"),
"CustomerName": "Ramit",
"CustomerAge": 23
}
{
"_id": ObjectId("5c9a5e4c15e86fd1496b38a3"),
"CustomerName": "Adam",
"CustomerAge": 27,
"CustomerCountryName": "US"
}
Method 1: Using countDocuments() (Recommended)
Count all documents in the collection ?
db.countNumberOfDocumentsDemo.countDocuments();
3
Method 2: Using count() (Legacy)
Alternative method using the legacy count() function ?
let myCollection = db.getCollection('countNumberOfDocumentsDemo');
myCollection.count();
3
Count with Query Filter
Count documents that match specific criteria ?
db.countNumberOfDocumentsDemo.countDocuments({"CustomerAge": {$exists: true}});
2
Key Points
-
countDocuments()provides accurate counts and supports aggregation pipeline filters. -
count()is faster but may return approximate results in sharded clusters. - Use query filters to count specific subsets of documents.
Conclusion
Use countDocuments() for accurate document counting in MongoDB collections. It supports optional query filters and provides reliable results across all MongoDB deployments.
Advertisements
