MongoDB में $group का उपयोग निर्दिष्ट _id एक्सप्रेशन द्वारा इनपुट दस्तावेज़ों को ग्रुप करने के लिए किया जाता है। आइए दस्तावेज़ों के साथ एक संग्रह बनाएं:
> db.demo466.insertOne( ... { ... ... "ProductPrice" :150, ... "ProductQuantity" : 1, ... "ProductName" : "Product-1", ... "ActualAmount" :110, ... "ProductProfit" : 40, ... "ProductId" : 1 ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e80477cb0f3fa88e2279066") } > > db.demo466.insertOne( ... { ... ... "ProductPrice" :150, ... "ProductQuantity" : 1, ... "ProductName" : "Product-1", ... "ActualAmount" :110, ... "ProductProfit" : 40, ... "ProductId" : 2 ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e80477db0f3fa88e2279067") } > db.demo466.insertOne( ... { ... ... "ProductPrice" :170, ... "ProductQuantity" : 2, ... "ProductName" : "Product-2", ... "ActualAmount" :130, ... "ProductProfit" : 50, ... "ProductId" : 3 ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e80477eb0f3fa88e2279068") }
सभी दस्तावेज़ प्रदर्शित करें
> db.demo466.find();
आउटपुट:
{ "_id" : ObjectId("5e80477cb0f3fa88e2279066"), "ProductPrice" : 150, "ProductQuantity" : 1, "ProductName" : "Product-1", "ActualAmount" : 110, "ProductProfit" : 40, "ProductId" : 1 } { "_id" : ObjectId("5e80477db0f3fa88e2279067"), "ProductPrice" : 150, "ProductQuantity" : 1, "ProductName" : "Product-1", "ActualAmount" : 110, "ProductProfit" : 40, "ProductId" : 2 } { "_id" : ObjectId("5e80477eb0f3fa88e2279068"), "ProductPrice" : 170, "ProductQuantity" : 2, "ProductName" : "Product-2", "ActualAmount" : 130, "ProductProfit" : 50, "ProductId" : 3 }
नेस्टेड $group और $sum का उपयोग करने की क्वेरी
> db.demo466.aggregate([ ... { ... '$group': { ... '_id': { ... 'ProductName': '$ProductName', ... }, ... 'ActualAmount': {'$sum': '$ActualAmount'}, ... 'ProductQuantity': {'$sum': '$ProductQuantity'}, ... 'ProductId': {'$addToSet': '$ProductId'}, ... }, ... }, ... { ... '$project': { ... 'ProductQuantity': true, ... 'ActualAmount': true, ... 'NumberOfProductInStock': {'$size': '$ProductId'} ... } ... }])
आउटपुट
{ "_id" : { "ProductName" : "Product-2" }, "ActualAmount" : 130, "ProductQuantity" : 2, "NumberOfProductInStock" : 1 } { "_id" : { "ProductName" : "Product-1" }, "ActualAmount" : 220, "ProductQuantity" : 2, "NumberOfProductInStock" : 2 }