Array items group करने के लिए $group के साथ $sort का उपयोग करें।
Collection बनाना
> db.demo566.insertOne(
... {
... "ProductInformation" : [
... { "ProductName" : "Product-1", "ProductPrice" :100 },
... { "ProductName" : "Product-2", "ProductPrice" :1100 },
... { "ProductName" : "Product-3", "ProductPrice" :100 },
... { "ProductName" : "Product-4", "ProductPrice" :1100 },
... { "ProductName" : "Product-5", "ProductPrice" :100 }
... ]
... }
... );
{ "acknowledged" : true, "insertedId" : ObjectId("5e908e2339cfeaaf0b97b57a") }
सभी Documents Display करना
> db.demo566.find();
Output:
{ "_id" : ObjectId("5e908e2339cfeaaf0b97b57a"), "ProductInformation" : [ { "ProductName" : "Product-1", "ProductPrice" : 100 }, { "ProductName" : "Product-2", "ProductPrice" : 1100 }, { "ProductName" : "Product-3", "ProductPrice" : 100 }, { "ProductName" : "Product-4", "ProductPrice" : 1100 }, { "ProductName" : "Product-5", "ProductPrice" : 100 } ] }
Array Items Group करने का Query
> db.demo566.aggregate([
... { "$unwind": "$ProductInformation" },
... { "$group": { "_id": "$ProductInformation.ProductPrice", "Value": { "$sum" : 1 } } },
... { "$sort": { "_id" :1 } }
... ])
Output:
{ "_id" : 100, "Value" : 3 }
{ "_id" : 1100, "Value" : 2 }
व्याख्या: $unwind array को flatten करता है (प्रत्येक element के लिए separate document)। फिर $group ने ProductPrice द्वारा group करके $sum: 1 से count किया। $sort ने price द्वारा ascending order में sort किया।