求 MongoDB 文档中重复列值的总得分?


要对不同文档中的值求和,请使用 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" }

更新于:13-5-2020

137 次浏览

开启你的职业生涯

完成课程以获得认证

开始
广告