Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

Tổng điểm của các giá trị trùng lặp cột trong tài liệu MongoDB

Để cộng dồn giá trị từ nhiều tài liệu có cùng tên, sử dụng $group trong aggregation. Tạo collection:

> 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") }

Hiển thị dữ liệu (Chris 2 bản ghi, Bob 2 bản ghi):

> db.demo512.find();

Kết quả:

Pipeline: $group theo Name, tính tổng Score1, Score2, lấy CountryName đầu tiên, $project định dạng, $out lưu vào collection mới demo513:

> 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" }
])

Hiển thị collection mới demo513:

> db.demo513.find();

Kết quả - Chris: Score1=86, Score2=110; Bob: Score1=140, Score2=145:

Lưu ý: $out ghi đè collection đích. Dùng $merge (MongoDB 4.2+) để upsert thay vì replace.