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 can I count the documents in an array based on the value of a specific field?
To count documents in an array based on the value of a specific field, use the $unwind operator to flatten the array, followed by $match to filter, and $group to count the matching elements.
Syntax
db.collection.aggregate([
{ $unwind: "$arrayField" },
{ $match: { "arrayField.fieldName": "targetValue" } },
{ $group: {
_id: null,
count: { $sum: 1 }
}}
]);
Sample Data
db.demo726.insertOne({
"id": 101,
"details": [
{ "Name": "Chris" },
{ "Name": "Chris" },
{ "Name": "Bob" }
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5eab318643417811278f5894")
}
Example: Count Array Elements by Field Value
Display all documents from the collection ?
db.demo726.find();
{
"_id": ObjectId("5eab318643417811278f5894"),
"id": 101,
"details": [
{ "Name": "Chris" },
{ "Name": "Chris" },
{ "Name": "Bob" }
]
}
Count how many array elements have Name = "Chris" ?
db.demo726.aggregate([
{ $unwind: "$details" },
{ $match: { "details.Name": "Chris" } },
{ $group: {
_id: null,
Total_Value: { $sum: 1 }
}}
]);
{ "_id": null, "Total_Value": 2 }
How It Works
-
$unwindcreates separate documents for each array element -
$matchfilters documents where the field matches the target value -
$groupcounts the remaining documents with$sum: 1
Conclusion
Use the aggregation pipeline with $unwind, $match, and $group to count array elements based on field values. This approach efficiently flattens arrays and counts matching elements.
Advertisements
