MongoDB 聚合多个结果?
如需聚合多个结果,请在 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" } ] }
广告