Dùng toán tử $add trong stage $project của aggregation để tổng hai trường số.
Ví dụ: Collection sumTwoFieldsDemo:
> db.sumTwoFieldsDemo.insertOne({ "FirstValue": 150, "SecondValue": 350 });
> db.sumTwoFieldsDemo.insertOne({ "FirstValue": 450, "SecondValue": 1550 });
> db.sumTwoFieldsDemo.insertOne({ "FirstValue": 2560, "SecondValue": 2440 });
Aggregation tính tổng:
> db.sumTwoFieldsDemo.aggregate([
{ $project: {
First: "$FirstValue",
Second: "$SecondValue",
TotalValueOfBothFields: { $add: ["$FirstValue", "$SecondValue"] }
}}
]);
Kết quả:
{ "_id": ..., "First": 150, "Second": 350, "TotalValueOfBothFields": 500 }
{ "_id": ..., "First": 450, "Second": 1550, "TotalValueOfBothFields": 2000 }
{ "_id": ..., "First": 2560, "Second": 2440, "TotalValueOfBothFields": 5000 }
Mở rộng: $add cũng dùng cho Date (cộng milliseconds) và Array (concat). Các toán tử số học khác: $subtract, $multiply, $divide, $mod.