Để lấy các cặp đối tượng distinct (duy nhất) và tính tổng, sử dụng $group trong aggregation. Tạo collection:
> db.demo522.insertOne({"Name":"John","Score":45});
{ "acknowledged" : true, "insertedId" : ObjectId("5e89b646b3fbf26334ef611b") }
> db.demo522.insertOne({"Name":"Bob","Score":67});
{ "acknowledged" : true, "insertedId" : ObjectId("5e89b64eb3fbf26334ef611c") }
> db.demo522.insertOne({"Name":"John","Score":55});
{ "acknowledged" : true, "insertedId" : ObjectId("5e89b655b3fbf26334ef611d") }
> db.demo522.insertOne({"Name":"Bob","Score":33});
{ "acknowledged" : true, "insertedId" : ObjectId("5e89b65cb3fbf26334ef611e") }
Hiển thị dữ liệu:
> db.demo522.find();
Kết quả:
Pipeline:
$grouptheo Name, tính tổng Score,$projectđịnh dạng lại output:> var query = [ { "$group": { "_id": "$Name", "Score": { "$sum": "$Score" } } }, { "$project": { "Name": "$_id", "_id": 0, "Score": 1 } } ]; > db.demo522.aggregate(query);Kết quả - mỗi tên xuất hiện 1 lần với tổng điểm:
Giải thích:
$groupvới_id: "$Name"tạo nhóm distinct theo Name.$sum: "$Score"cộng dồn điểm.$projectđổi _id thành Name và ẩn _id gốc.