要聚合多个结果,请在MongoDB中使用$group。让我们创建一个包含文档的集合-
> db.demo765.insertOne( ... ... { ... Name:"John", ... "Category":"ComputerScience", ... "SubjectName":"MongoDB", ... "Marks":75 ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5eb054525637cd592b2a4b01") } > > db.demo765.insertOne( ... { ... Name:"John", ... "Category":"ComputerScience", ... "SubjectName":"MySQL", ... "Marks":85 ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5eb054525637cd592b2a4b02") } > db.demo765.insertOne( ... { ... Name:"Chris", ... "Category":"10th", ... "SubjectName":"Math", ... "Marks":98 ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5eb054535637cd592b2a4b03") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo765.find();
这将产生以下输出-
{ "_id" : ObjectId("5eb054525637cd592b2a4b01"), "Name" : "John", "Category" : "ComputerScience", "SubjectName" : "MongoDB", "Marks" : 75 } { "_id" : ObjectId("5eb054525637cd592b2a4b02"), "Name" : "John", "Category" : "ComputerScience", "SubjectName" : "MySQL", "Marks" : 85 } { "_id" : ObjectId("5eb054535637cd592b2a4b03"), "Name" : "Chris", "Category" : "10th", "SubjectName" : "Math", "Marks" : 98 }
以下是汇总组多个结果的查询-
> db.demo765.aggregate([ ... { "$facet": { ... "ListOfName": [ ... { "$group": { ... "_id": "$Name", ... "Marks": { "$sum": "$Marks" } ... }}, ... { "$project": { ... "_id": false, ... "Name": "$_id", ... "Marks": 1 ... }} ... ], ... "ListOfCategory": [ ... { "$group": { ... "_id": "$Category", ... "Marks": { "$sum": "$Marks" } ... }}, ... { "$project": { ... "_id": false, ... "Category": "$_id", ... "Marks": 1 ... }} ... ] ... }} ... ]).pretty()
这将产生以下输出-
{ "ListOfName" : [ { "Marks" : 98, "Name" : "Chris" }, { "Marks" : 160, "Name" : "John" } ], "ListOfCategory" : [ { "Marks" : 98, "Category" : "10th" }, { "Marks" : 160, "Category" : "ComputerScience" } ] }