首先让我们创建一个包含文档的集合-
> db.demo121.insertOne( ... { ... "Id" : 101, ... "Details" : [ ... { ... "SubjectId" : "1", ... "SubjectName" : "MongoDB", ... "Score" : 76 ... }, ... { ... "SubjectId" : "2", ... "SubjectName" : "MySQL", ... "Score" : 76 ... }, ... { ... "SubjectId" : "3", ... "SubjectName" : "Java", ... "Score" : 76 ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e2f1c60140daf4c2a3544b3") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo121.find();
这将产生以下输出-
{ "_id" : ObjectId("5e2f1c60140daf4c2a3544b3"), "Id" : 101, "Details" : [ { "SubjectId" : "1", "SubjectName" : "MongoDB", "Score" : 76 }, { "SubjectId" : "2", "SubjectName" : "MySQL", "Score" : 76 }, { "SubjectId" : "3", "SubjectName" : "Java", "Score" : 76 } ] }
以下是实现聚合功能的查询-
> db.demo121.aggregate([ ... { "$match": { "Id": 101 } }, ... { "$unwind": "$Details" }, ... { ... "$group": { ... "_id": "$Details.SubjectId", ... "count": { "$sum": 1 }, ... "Details": { ... "$push": { ... "SubjectName": "$Details.SubjectName" ... } ... } ... } ... }, ... { ... "$group": { ... "_id": null, ... "List": { ... "$push": { ... "SubId": "$_id", ... "Details": "$Details" ... } ... } ... } ... } ... ], function (err, out) { ... res.json(out); ... });
这将产生以下输出-
{ "_id" : null, "List" : [ { "SubId" : "3", "Details" : [ { "SubjectName" : "Java" } ] }, { "SubId" : "2", "Details" : [ { "SubjectName" : "MySQL" } ] }, { "SubId" : "1", "Details" : [ { "SubjectName" : "MongoDB" } ] } ] }