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 do I use MongoDB to count only collections that match two fields?
To count documents in MongoDB that match multiple field conditions, use the count() method with a query document containing all required field−value pairs. MongoDB will return the count of documents where all specified conditions are satisfied.
Syntax
db.collection.count({
"field1": "value1",
"field2": "value2"
});
Sample Data
db.demo175.insertMany([
{"EmployeeName": "Bob", "isMarried": "YES"},
{"EmployeeName": "David", "isMarried": "NO"},
{"EmployeeName": "Mike", "isMarried": "YES"},
{"EmployeeName": "Sam", "isMarried": "NO"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e3840969e4f06af551997e8"),
ObjectId("5e38409e9e4f06af551997e9"),
ObjectId("5e3840a79e4f06af551997ea"),
ObjectId("5e3840ae9e4f06af551997eb")
]
}
Display all documents from the collection ?
db.demo175.find();
{"_id": ObjectId("5e3840969e4f06af551997e8"), "EmployeeName": "Bob", "isMarried": "YES"}
{"_id": ObjectId("5e38409e9e4f06af551997e9"), "EmployeeName": "David", "isMarried": "NO"}
{"_id": ObjectId("5e3840a79e4f06af551997ea"), "EmployeeName": "Mike", "isMarried": "YES"}
{"_id": ObjectId("5e3840ae9e4f06af551997eb"), "EmployeeName": "Sam", "isMarried": "NO"}
Example: Count Documents Matching Two Fields
Count documents where EmployeeName is "Mike" AND isMarried is "YES" ?
db.demo175.count({
"EmployeeName": "Mike",
"isMarried": "YES"
});
1
Key Points
- Multiple fields in the query document create an AND condition − all must match.
- Use
countDocuments()as a modern alternative to the deprecatedcount()method. - For OR conditions, use
$oroperator within the query document.
Conclusion
The count() method with multiple field conditions efficiently counts documents matching all specified criteria. This provides a quick way to get document counts based on complex filtering requirements.
Advertisements
