आइए दस्तावेजों के साथ एक संग्रह बनाएं -
> db.demo136.insertOne( ... { ... ... "Name":"Chris", ... "Details":[ ... { ... "Id":"101", ... "EmployeeName":"Mike", ... "EmployeeDetails":[ ... { ... "EmpId":1001, ... "Salary":1000 ... }, ... { ... "EmpId":1002, ... "Salary":2000 ... } ... ] ... }, ... { ... "Id":"102", ... "EmployeeName":"David", ... "EmployeeDetails":[ ... { ... "EmpId":1004, ... "Salary":4000 ... }, ... { ... "EmpId":1005, ... "Salary":5000 ... } ... ] ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e31b15cfdf09dd6d085399f") }
संग्रह से सभी दस्तावेज़ों को खोजने () विधि की सहायता से प्रदर्शित करें -
> db.demo136.find();
यह निम्नलिखित आउटपुट देगा -
{ "_id" : ObjectId("5e31b15cfdf09dd6d085399f"), "Name" : "Chris", "Details" : [ { "Id" : "101", "EmployeeName" : "Mike", "EmployeeDetails" : [ { "EmpId" : 1001, "Salary" : 1000 }, { "EmpId" : 1002, "Salary" : 2000 } ] }, { "Id" : "102", "EmployeeName" : "David", "EmployeeDetails" : [ { "EmpId" : 1004, "Salary" : 4000 }, { "EmpId" : 1005, "Salary" : 5000 } ] } ] }
उप-दस्तावेज़ों को छाँटने की क्वेरी निम्नलिखित है -
> db.demo136.aggregate([ ... { $unwind: "$Details" }, ... { ... $project: { ... Name: 1, ... Details: 1, ... SalaryTotal: { ... $sum: "$Details.EmployeeDetails.Salary" ... } ... } ... }, ... { $sort: { SalaryTotal: -1 } }, ... { ... $group: { ... _id: "$_id", ... Name: { $first: "$Name" }, ... Details: { $push: "$Details" } ... } ... } ... ]).pretty()
यह निम्नलिखित आउटपुट देगा -
{ "_id" : ObjectId("5e31b15cfdf09dd6d085399f"), "Name" : "Chris", "Details" : [ { "Id" : "102", "EmployeeName" : "David", "EmployeeDetails" : [ { "EmpId" : 1004, "Salary" : 4000 }, { "EmpId" : 1005, "Salary" : 5000 } ] }, { "Id" : "101", "EmployeeName" : "Mike", "EmployeeDetails" : [ { "EmpId" : 1001, "Salary" : 1000 }, { "EmpId" : 1002, "Salary" : 2000 } ] } ] }