MongoDB में ऐरे मान के आधार पर एग्रीगेशन
इसके लिए MongoDB में aggregate() का उपयोग करें।
कलेक्शन बनाना
> db.demo126.insertOne(
{
"StudentDetails": {
"Number": 1,
"OtherDetails": [
{ "Name": "Chris", "Score": 55 }
]
}
}
);
{ "acknowledged": true, "insertedId": ObjectId("5e304b3068e7f832db1a7f56") }
> db.demo126.insertOne(
{
"StudentDetails": {
"Number": 2,
"OtherDetails": [
{ "Name": "Chris", "Score": 35 },
{ "Name": "David", "Score": 87 }
]
}
}
);
{ "acknowledged": true, "insertedId": ObjectId("5e304b3068e7f832db1a7f57") }
सभी डॉक्यूमेंट्स
> db.demo126.find();
{ "_id": ObjectId("5e304b3068e7f832db1a7f56"), "StudentDetails": { "Number": 1, "OtherDetails": [ { "Name": "Chris", "Score": 55 } ] } }
{ "_id": ObjectId("5e304b3068e7f832db1a7f57"), "StudentDetails": { "Number": 2, "OtherDetails": [ { "Name": "Chris", "Score": 35 }, { "Name": "David", "Score": 87 } ] } }
एग्रीगेशन क्वेरी
> db.demo126.aggregate([
{ $unwind: "$StudentDetails.OtherDetails" },
{
$group: {
_id: "$StudentDetails.OtherDetails.Name",
quantity: { $sum: "$StudentDetails.OtherDetails.Score" }
}
}
])
परिणाम
{ "_id": "David", "quantity": 87 }
{ "_id": "Chris", "quantity": 90 }
व्याख्या
- $unwind: StudentDetails.OtherDetails ऐरे को अलग-अलग डॉक्यूमेंट्स में फैलाता है
- $group: Name के अनुसार ग्रुप करता है (_id: "$StudentDetails.OtherDetails.Name")
- $sum: प्रत्येक नाम के लिए Score जोड़ता है
- Chris: 55 + 35 = 90
- David: 87
यह पैटर्न नेस्टेड ऐरे में विभिन्न पैरेंट डॉक्यूमेंट्स में बच्चे तत्वों के मानों को जोड़ने के लिए उपयोगी है।