聚合同层数组的 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 } ] } ] }
广告