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

更新日期:2019 年 7 月 30 日

272 次浏览

开启您的职业生涯

完成课程,获得认证

入门
广告
© . All rights reserved.