MongoDB में नेस्टेड दस्तावेज़ों को एकत्रित करने के लिए, आप $group का उपयोग कर सकते हैं। आइए पहले दस्तावेजों के साथ एक संग्रह बनाएं -
> db.aggregateDemo.insertOne(
... {
... "ProductInformation": [
... {
... "Product1": [
... {
... Amount: 50
... },
... {
... Amount: 90
... },
... {
... Amount: 30
... }
... ]
... },
... {
... "Product1": [
... {
... Amount: 200
... },
... {
... Amount: 30
... },
... {
... Amount: 40
... }
... ]
... },
... {
... "Product1": [
... {
... Amount: 150
... },
... {
... Amount: 190
... },
... {
... Amount: 198
... }
... ]
... }
...
... ]
... });
{
"acknowledged" : true,
"insertedId" : ObjectId("5e04df58150ee0e76c06a04d")
}
> db.aggregateDemo.insertOne(
... {
... "ProductInformation": [
... {
... "Product1": [
... {
... Amount: 100
... },
... {
... Amount: 1002
... },
... {
... Amount: 78
... }
... ]
... },
... {
... "Product1": [
... {
... Amount: 75
... },
... {
... Amount: 400
... },
... {
... Amount: 600
... }
... ]
... },
... {
... "Product1": [
... {
... Amount: 700
... },
... {
... Amount: 500
... },
... {
... Amount: 600
... }
... ]
... }
...
... ]
... });
{
"acknowledged" : true,
"insertedId" : ObjectId("5e04df93150ee0e76c06a04e")
} खोज () विधि की मदद से संग्रह से सभी दस्तावेजों को प्रदर्शित करने के लिए क्वेरी निम्नलिखित है -
> db.aggregateDemo.find().pretty();
यह निम्नलिखित आउटपुट उत्पन्न करेगा -
{
"_id" : ObjectId("5e04df58150ee0e76c06a04d"),
"ProductInformation" : [
{
"Product1" : [
{
"Amount" : 50
},
{
"Amount" : 90
},
{
"Amount" : 30
}
]
},
{
"Product1" : [
{
"Amount" : 200
},
{
"Amount" : 30
},
{
"Amount" : 40
}
]
},
{
"Product1" : [
{
"Amount" : 150
},
{
"Amount" : 190
},
{
"Amount" : 198
}
]
}
]
}
{
"_id" : ObjectId("5e04df93150ee0e76c06a04e"),
"ProductInformation" : [
{
"Product1" : [
{
"Amount" : 100
},
{
"Amount" : 1002
},
{
"Amount" : 78
}
]
},
{
"Product1" : [
{
"Amount" : 75
},
{
"Amount" : 400
},
{
"Amount" : 600
}
]
},
{
"Product1" : [
{
"Amount" : 700
},
{
"Amount" : 500
},
{
"Amount" : 600
}
]
}
]
} यहाँ नेस्टेड दस्तावेज़ों को एकत्रित करने के लिए क्वेरी है -
> db.aggregateDemo.aggregate([
... {
... $unwind:"$ProductInformation"
... },
... {
... $unwind:"$ProductInformation.Product1"
... },
... {
... $group:{
... _id:null,
... MaximumAmount:{
... $max:"$ProductInformation.Product1.Amount"
... }
... }
... }
... ]); यह निम्नलिखित आउटपुट उत्पन्न करेगा -
{ "_id" : null, "MaximumAmount" : 1002 }