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

Trừ giá trị trường tài liệu trong MongoDB aggregation ($subtract)

Sử dụng toán tử $subtract trong aggregation $project để tính hiệu hai trường số (TotalPrice - DiscountPrice). Tạo collection:

> db.demo599.insertOne({"TotalPrice":250,"DiscountPrice":35});
{ "acknowledged" : true, "insertedId" : ObjectId("5e948192f5f1e70e134e2696") }
> db.demo599.insertOne({"TotalPrice":400,"DiscountPrice":10});
{ "acknowledged" : true, "insertedId" : ObjectId("5e948199f5f1e70e134e2697") }
> db.demo599.insertOne({"TotalPrice":1550,"DiscountPrice":50});
{ "acknowledged" : true, "insertedId" : ObjectId("5e9481a0f5f1e70e134e2698") }

Hiển thị dữ liệu:

> db.demo599.find();

Aggregation tính ActualPrice = TotalPrice - DiscountPrice:

> db.demo599.aggregate([ { $project: { ActualPrice: { $subtract: [ "$TotalPrice", "$DiscountPrice" ] } } } ]);

Kết quả:


Các toán tử arithmetic trong $project: $add, $subtract, $multiply, $divide, $mod. Đều nhận mảng 2 phần tử: [expression1, expression2].