MongoDB按子文档进行排序匹配吗?

要按子文档匹配项排序,可以使用聚合框架。首先让我们创建一个包含文档的集合-

> db.sortBySubDocumentsDemo.insertOne(
   {
      "StudentName": "Chris",
      "StudentDetails": [
         {
            "Age":21,
            "StudentScore":91
         },
         {
            "Age":22,
            "StudentScore":99
         },
         {
            "Age":21,
            "StudentScore":93
         }
      ]
   }
);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd57e297924bb85b3f48942")
}
> db.sortBySubDocumentsDemo.insertOne(
   {
      "StudentName": "Robert",
      "StudentDetails": [
         {
            "Age":24,
            "StudentScore":78
         },
         {
            "Age":21,
            "StudentScore":86
         },
         {
            "Age":23,
            "StudentScore":45
         }
      ]
   }
);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd57e4c7924bb85b3f48943")
}

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

> db.sortBySubDocumentsDemo.find().pretty();

这将产生以下输出-

{
   "_id" : ObjectId("5cd57e297924bb85b3f48942"),
   "StudentName" : "Chris",
   "StudentDetails" : [
      {
         "Age" : 21,
         "StudentScore" : 91
      },
      {
         "Age" : 22,
         "StudentScore" : 99
      },
      {
         "Age" : 21,
         "StudentScore" : 93
      }
   ]
}
{
   "_id" : ObjectId("5cd57e4c7924bb85b3f48943"),
   "StudentName" : "Robert",
   "StudentDetails" : [
      {
         "Age" : 24,
         "StudentScore" : 78
      },
      {
         "Age" : 21,
         "StudentScore" : 86
      },
      {
         "Age" : 23,
         "StudentScore" : 45
      }
   ]
}

以下是按子文档匹配项排序的查询。在这里,我们按StudentScore进行排序-

> db.sortBySubDocumentsDemo.aggregate([
   {$match: { 'StudentDetails.Age': 21 }},
   {$unwind: '$StudentDetails'},
   {$match: {'StudentDetails.Age': 21}},
   {$project: {_id: 0, "StudentName": 1, 'StudentDetails.StudentScore': 1}},
   {$sort: { 'StudentDetails.StudentScore': 1 }},
   {$limit: 5}
]);

这将产生以下输出-

{ "StudentName" : "Robert", "StudentDetails" : { "StudentScore" : 86 } }
{ "StudentName" : "Chris", "StudentDetails" : { "StudentScore" : 91 } }
{ "StudentName" : "Chris", "StudentDetails" : { "StudentScore" : 93 } }