为此,将aggregate()与$group一起使用。让我们创建一个包含文档的集合-
> db.demo578.insertOne( ... { ... "_id" : 1, ... "Info" : { ... "firstName" : "Chris", ... "lastName" : "Brown" ... }, ... ... "achievements" : [ ... { ... "winner" : "10th", ... "year" : 2010, ... "by" : "School" ... }, ... { ... "winner" : "12th", ... "year" : 2012, ... "by" : "School" ... }, ... { ... "winner" : "Good Rank", ... "year" : 2012, ... "by" : "College" ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : 1 }
在find()方法的帮助下显示集合中的所有文档-
> db.demo578.find();
这将产生以下输出-
{ "_id" : 1, "Info" : { "firstName" : "Chris", "lastName" : "Brown" }, "achievements" : [ { "winner" : "10th", "year" : 2010, "by" : "School" }, { "winner" : "12th", "year" : 2012, "by" : "School" }, { "winner" : "Good Rank", "year" : 2012, "by" : "College" } ] }
以下是对数组内具有相等聚合的查询-
> db.demo578.aggregate([ ... { ... "$unwind": "$achievements" ... }, ... { ... "$group": { ... "_id": { ... "year": "$achievements.year", ... "firstName": "$Info.firstName", ... "lastName": "$Info.lastName" ... }, ... "count": { "$sum": 1 }, ... "AchievementName": { "$push": "$Info" } ... } ... }, ... { ... "$match": { "count": 2 } ... }, ... { ... "$project": { ... "_id": 0, ... "year": "$_id.year", ... "AchievementName": 1, ... "count": 1 ... } ... } ... ]).pretty();
这将产生以下输出-
{ "count" : 2, "AchievementName" : [ { "firstName" : "Chris", "lastName" : "Brown" }, { "firstName" : "Chris", "lastName" : "Brown" } ], "year" : 2012 }