इसके लिए MongoDB में समुच्चय () का उपयोग करें। आइए पहले दस्तावेजों के साथ एक संग्रह बनाएं -
> 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 }