To subtract values from document field values, use $subtract in MongoDB aggregate(). Let us create a collection with documents −
> 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")
}Display all documents from a collection with the help of find() method −
> db.demo599.find();
This will produce the following output −
{ "_id" : ObjectId("5e948192f5f1e70e134e2696"), "TotalPrice" : 250, "DiscountPrice" : 35 }
{ "_id" : ObjectId("5e948199f5f1e70e134e2697"), "TotalPrice" : 400, "DiscountPrice" : 10 }
{ "_id" : ObjectId("5e9481a0f5f1e70e134e2698"), "TotalPrice" : 1550, "DiscountPrice" : 50 }Following is the query to subtract values from document field values −
> db.demo599.aggregate( [ { $project: {ActualPrice: { $subtract: [ "$TotalPrice", "$DiscountPrice" ] } } } ] )This will produce the following output −
{ "_id" : ObjectId("5e948192f5f1e70e134e2696"), "ActualPrice" : 215 }
{ "_id" : ObjectId("5e948199f5f1e70e134e2697"), "ActualPrice" : 390 }
{ "_id" : ObjectId("5e9481a0f5f1e70e134e2698"), "ActualPrice" : 1500 }