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
GROUP BY array of document to get the count of repeated Age values
To GROUP BY array of document to get count of repeated Age values, use the aggregation pipeline with $unwind to flatten the array and $group to count occurrences by Age.
Syntax
db.collection.aggregate([
{ $unwind: "$arrayField" },
{ $group: { _id: "$arrayField.groupingField", count: { $sum: 1 } } },
{ $sort: { _id: 1 } }
]);
Sample Data
db.demo559.insertOne({
details: [
{ Name: "Chris", Age: 21 },
{ Name: "Bob", Age: 22 },
{ Name: "Carol", Age: 21 },
{ Name: "Sam", Age: 21 }
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5e8f38d954b4472ed3e8e866")
}
Verify Sample Data
db.demo559.find().pretty();
{
"_id": ObjectId("5e8f38d954b4472ed3e8e866"),
"details": [
{ "Name": "Chris", "Age": 21 },
{ "Name": "Bob", "Age": 22 },
{ "Name": "Carol", "Age": 21 },
{ "Name": "Sam", "Age": 21 }
]
}
Group by Age and Count Occurrences
db.demo559.aggregate([
{ $unwind: "$details" },
{ $group: {
_id: "$details.Age",
Count: { $sum: 1 }
}},
{ $sort: { _id: 1 } }
]);
{ "_id": 21, "Count": 3 }
{ "_id": 22, "Count": 1 }
How It Works
-
$unwind − Flattens the
detailsarray, creating separate documents for each array element -
$group − Groups documents by
Agefield and counts occurrences using$sum: 1 - $sort − Sorts results by Age in ascending order
Conclusion
Use $unwind to deconstruct arrays, then $group with $sum: 1 to count repeated values. This pattern effectively transforms nested array data into grouped aggregation results.
Advertisements
