Sử dụng $divide trong pipeline $project của aggregation framework.
Tạo collection
> db.aggregationOperatorDemo.insertOne({ "FirstValue": 392883, "SecondValue": 10000000000 });
{ "acknowledged": true, "insertedId": ObjectId("5cd541452cba06f46efe9f01") }
Hiển thị tài liệu
> db.aggregationOperatorDemo.find().pretty();
Tính FirstValue / SecondValue
> db.aggregationOperatorDemo.aggregate([
{ $project: { Value: { $divide: ["$FirstValue", "$SecondValue"] } } }
]);
Kết quả:
{ "_id": ObjectId("5cd541452cba06f46efe9f01"), "Value": 0.0000392883 }
Giải thích: $divide nhận mảng hai phần tử: [biểu_thức_chia, biểu_thức_chia_cho]. Kết quả là số thực (double). Cũng có thể dùng trong $project kết hợp các toán tử số học khác: $add, $subtract, $multiply, $mod.