Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

MongoDB query sắp xếp subdocument theo tổng lương

Sắp xếp lại thứ tự subdocument trong mảng Details dựa trên tổng Salary của mảng EmployeeDetails con.

Tạo collection demo136 với cấu trúc lồng 3 cấp:

> 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}]}
   ]
});

Pipeline: unwind Details, project tính SalaryTotal = sum EmployeeDetails.Salary, sort giảm dần, group lại push Details:

> 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()

Kết quả: David (tổng 9000) lên trước Mike (tổng 3000):

{
   "_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}]}
   ]
}