MongoDB中如何查询聚合嵌套数组

要在MongoDB中聚合嵌套数组,请使用aggregate()。让我们创建一个包含文档的集合-

> db.demo441.insertOne(
...    {
...
...       "Name" : "David",
...       "Age" : 21,
...
...       "details" : [
...          {
...             "id" : 1,
...             "CountryName" : "US",
...             "details1" : [
...                {
...                   "SubjectName" : "MySQL",
...                   "Score":56
...                },
...                {
...                   "SubjectName" : "MongoDB",
...                   "Score":78
...                }
...             ]
...          }
...       ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e78cc05bbc41e36cc3caeb7")
}

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

> db.demo441.find();

这将产生以下输出-

{ "_id" : ObjectId("5e78cc05bbc41e36cc3caeb7"), "Name" : "David", "Age" : 21, "details" : [ { "id" : 1, "CountryName" : "US", "details1" : [ { "SubjectName" : "MySQL", "Score" : 56 }, { "SubjectName" : "MongoDB", "Score" : 78 } ] } ] }

以下是聚合嵌套数组的查询-

> db.demo441.aggregate([{
...    $addFields: {
...       ResultOfDetails: {
...          $map: {
...             input: "$details",
...             as: "output",
...             in: {
...                id: "$$output.id",
...                CountryName: "$$output.CountryName",
...                details1: {
...                   $let: {
...                      vars: {
...                         last: {
...                            $arrayElemAt: ["$$output.details1", -1]
...                         }
...                      },
...                      in: {
...                         $cond: [{
...                            $eq: ["$$last.Score", 78]
...                         },
...                      ["$$last"],
...                         []
...
...                      }
...                   }
...                }
...             }
...          }
...       }
...    }
... }]).pretty();

这将产生以下输出-

{
   "_id" : ObjectId("5e78cc05bbc41e36cc3caeb7"),
   "Name" : "David",
   "Age" : 21,
   "details" : [
      {
         "id" : 1,
         "CountryName" : "US",
         "details1" : [
            {
               "SubjectName" : "MySQL",
               "Score" : 56
            },
            {
               "SubjectName" : "MongoDB",
               "Score" : 78
            }
         ]
      }
   ],
   "ResultOfDetails" : [
      {
         "id" : 1,
         "CountryName" : "US",
         "details1" : [
            {
               "SubjectName" : "MongoDB",
               "Score" : 78
            }
         ]
      }  
   ]
}