MongoDB查询对子文档进行排序

让我们创建一个包含文档的集合-

> 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")
}

在find()方法的帮助下显示集合中的所有文档-

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