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 group nested fields in MongoDB aggregation with count value in array?
To group nested fields in MongoDB aggregation with count values from arrays, use the $objectToArray operator to convert nested objects into key-value pairs, then use $unwind and $group to aggregate the count values.
Syntax
db.collection.aggregate([
{ $project: { fieldName: { $objectToArray: "$nestedObject" } } },
{ $unwind: "$fieldName" },
{ $group: { _id: "$fieldName.k", count: { $sum: "$fieldName.v.countField" } } }
])
Sample Data
db.demo99.insertMany([
{
"Details": {
"X": {
"Values": [10, 30, 50],
"Number": 3
},
"Y": {
"Values": [1000, 180],
"Number": 2
}
}
},
{
"Details": {
"X": {
"Values": [100, 300, 500, 6000],
"Number": 4
},
"Y": {
"Values": [10, 20, 60],
"Number": 3
}
}
}
])
{
"acknowledged": true,
"insertedIds": [
ObjectId("..."),
ObjectId("...")
]
}
Display Sample Data
db.demo99.find()
{ "_id" : ObjectId("5e2d91eab8903cdd865577b9"), "Details" : { "X" : { "Values" : [ 10, 30, 50 ], "Number" : 3 }, "Y" : { "Values" : [ 1000, 180 ], "Number" : 2 } } }
{ "_id" : ObjectId("5e2d927bb8903cdd865577ba"), "Details" : { "X" : { "Values" : [ 100, 300, 500, 6000 ], "Number" : 4 }, "Y" : { "Values" : [ 10, 20, 60 ], "Number" : 3 } } }
Group Nested Fields with Count
db.demo99.aggregate([
{ $project: { Count: { $objectToArray: "$Details" } } },
{ $unwind: "$Count" },
{ $group: { _id: "$Count.k", count: { $sum: "$Count.v.Number" } } }
])
{ "_id" : "Y", "count" : 5 }
{ "_id" : "X", "count" : 7 }
How It Works
- $objectToArray converts the nested "Details" object into an array of key-value pairs
- $unwind creates separate documents for each key-value pair
- $group groups by the key ("X" or "Y") and sums the "Number" values
Conclusion
Use $objectToArray, $unwind, and $group together to aggregate count values from nested object fields. This approach effectively transforms nested objects into groupable data structures for aggregation operations.
Advertisements
