MongoDB 查询以实现聚合函数
我们首先使用文档创建集合 -
> 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" } ] } ] }
广告