Tính tổng Score cho mỗi Name trong mảng OtherDetails lồng trong StudentDetails across các document.
Tạo collection demo126:
> db.demo126.insertOne({
"StudentDetails": {
"Number": 1,
"OtherDetails": [ {"Name":"Chris","Score":55} ]
}
});
> db.demo126.insertOne({
"StudentDetails": {
"Number": 2,
"OtherDetails": [
{"Name":"Chris","Score":35},
{"Name":"David","Score":87}
]
}
});
Pipeline: unwind OtherDetails, group theo Name tính sum Score:
> db.demo126.aggregate([
{ $unwind: "$StudentDetails.OtherDetails" },
{
$group: {
_id: "$StudentDetails.OtherDetails.Name",
quantity: { $sum: "$StudentDetails.OtherDetails.Score" }
}
}
])
Kết quả: Chris = 90, David = 87:
{ "_id" : "David", "quantity" : 87 }
{ "_id" : "Chris", "quantity" : 90 }