MongoDB的总和由多列组成,以计算具有重复ID的总分数
为此,请aggregate()
与$group一起使用。让我们创建一个包含文档的集合-
> db.demo627.insertOne({id:101,"Name":"Chris","Marks":54}); { "acknowledged" : true, "insertedId" : ObjectId("5e9acb306c954c74be91e6b2") } > db.demo627.insertOne({id:102,"Name":"Bob","Marks":74}); { "acknowledged" : true, "insertedId" : ObjectId("5e9acb3c6c954c74be91e6b3") } > db.demo627.insertOne({id:101,"Name":"Chris","Marks":87}); { "acknowledged" : true, "insertedId" : ObjectId("5e9acb426c954c74be91e6b4") } > db.demo627.insertOne({id:102,"Name":"Mike","Marks":70}); { "acknowledged" : true, "insertedId" : ObjectId("5e9acb4b6c954c74be91e6b5") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo627.find();
这将产生以下输出-
{ "_id" : ObjectId("5e9acb306c954c74be91e6b2"), "id" : 101, "Name" : "Chris", "Marks" : 54 } { "_id" : ObjectId("5e9acb3c6c954c74be91e6b3"), "id" : 102, "Name" : "Bob", "Marks" : 74 } { "_id" : ObjectId("5e9acb426c954c74be91e6b4"), "id" : 101, "Name" : "Chris", "Marks" : 87 } { "_id" : ObjectId("5e9acb4b6c954c74be91e6b5"), "id" : 102, "Name" : "Mike", "Marks" : 70 }
以下是对MongoDB组进行多列求和的查询,以计算具有重复ID的总计标记-
> db.demo627.aggregate([ ... { "$group": { ... "_id": { ... "id" : "$id", .. . "Name":"$Name" ... }, ... "Marks": { "$sum": "$Marks" } ... }}, ... { "$group": { ... "_id": { ... "id" : "$_id.id", ... "Name": "$_id.Name" ... }, ... ... "TotalMarks": { "$sum": "$Marks" } ... }} ... ], { "allowDiskUse": true } ... );
这将产生以下输出-
{ "_id" : { "id" : 101, "Name" : "Chris" }, "TotalMarks" : 141 } { "_id" : { "id" : 102, "Name" : "Bob" }, "TotalMarks" : 74 } { "_id" : { "id" : 102, "Name" : "Mike" }, "TotalMarks" : 70 }