要对不同文档中的值求和,请使用MongoDB $group。让我们创建一个包含文档的集合-
> db.demo512.insertOne({"Name":"Chris","Score1":45,"Score2":65,"CountryName":"US"});{ "acknowledged" : true, "insertedId" : ObjectId("5e884d96987b6e0e9d18f588") } > db.demo512.insertOne({"Name":"Chris","Score1":41,"Score2":45,"CountryName":"US"});{ "acknowledged" : true, "insertedId" : ObjectId("5e884da2987b6e0e9d18f589") } > db.demo512.insertOne({"Name":"Bob","Score1":75,"Score2":55,"CountryName":"US"});{ "acknowledged" : true, "insertedId" : ObjectId("5e884db2987b6e0e9d18f58a") } > db.demo512.insertOne({"Name":"Bob","Score1":65,"Score2":90,"CountryName":"US"});{ "acknowledged" : true, "insertedId" : ObjectId("5e884dc2987b6e0e9d18f58b") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo512.find();
这将产生以下输出-
{ "_id" : ObjectId("5e884d96987b6e0e9d18f588"), "Name" : "Chris", "Score1" : 45, "Score2" : 65, "CountryName" : "US" } { "_id" : ObjectId("5e884da2987b6e0e9d18f589"), "Name" : "Chris", "Score1" : 41, "Score2" : 45, "CountryName" : "US" } { "_id" : ObjectId("5e884db2987b6e0e9d18f58a"), "Name" : "Bob", "Score1" : 75, "Score2" : 55, "CountryName" : "US" } { "_id" : ObjectId("5e884dc2987b6e0e9d18f58b"), "Name" : "Bob", "Score1" : 65, "Score2" : 90, "CountryName" : "US" }
以下是对MongoDB中重复列值的分数求和的查询-
> db.demo512.aggregate([ ... { ... "$group": { ... "_id": "$Name", ... "Score1": { "$sum": "$Score1" }, ... "Score2": { "$sum": "$Score2" }, ... "CountryName": { "$first": "$CountryName" } ... } ... }, ... { ... "$project": { ... "_id": 0, ... "Name": "$_id", ... "Score1": 1, ... "Score2": 1, ... "CountryName": 1 ... } ... }, ... { "$out": "demo513" } ... ])
以下是显示结果的查询-
> db.demo513.find();
这将产生以下输出-
{ "_id" : ObjectId("5e884f0e79442efd15c6eae0"), "Score1" : 140, "Score2" : 145, "CountryName" : "US", "Name" : "Bob" } { "_id" : ObjectId("5e884f0e79442efd15c6eae1"), "Score1" : 86, "Score2" : 110, "CountryName" : "US", "Name" : "Chris" }