Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to subtract values (TotalPrice – Discount) from document field values in MongoDB?
To subtract values from document field values in MongoDB, use the $subtract operator within the aggregation pipeline. This operator performs arithmetic subtraction between numeric field values or expressions.
Syntax
db.collection.aggregate([
{
$project: {
newField: {
$subtract: ["$field1", "$field2"]
}
}
}
]);
Sample Data
db.demo599.insertMany([
{"TotalPrice": 250, "DiscountPrice": 35},
{"TotalPrice": 400, "DiscountPrice": 10},
{"TotalPrice": 1550, "DiscountPrice": 50}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e948192f5f1e70e134e2696"),
ObjectId("5e948199f5f1e70e134e2697"),
ObjectId("5e9481a0f5f1e70e134e2698")
]
}
Display Sample Data
db.demo599.find();
{ "_id": ObjectId("5e948192f5f1e70e134e2696"), "TotalPrice": 250, "DiscountPrice": 35 }
{ "_id": ObjectId("5e948199f5f1e70e134e2697"), "TotalPrice": 400, "DiscountPrice": 10 }
{ "_id": ObjectId("5e9481a0f5f1e70e134e2698"), "TotalPrice": 1550, "DiscountPrice": 50 }
Calculate Actual Price (TotalPrice - DiscountPrice)
db.demo599.aggregate([
{
$project: {
ActualPrice: {
$subtract: ["$TotalPrice", "$DiscountPrice"]
}
}
}
]);
{ "_id": ObjectId("5e948192f5f1e70e134e2696"), "ActualPrice": 215 }
{ "_id": ObjectId("5e948199f5f1e70e134e2697"), "ActualPrice": 390 }
{ "_id": ObjectId("5e9481a0f5f1e70e134e2698"), "ActualPrice": 1500 }
Key Points
-
$subtracttakes an array with exactly two numeric expressions:[$minuend, $subtrahend] - Field references must be prefixed with
$(e.g.,"$TotalPrice") - The operator only projects the calculated field by default; use
$$ROOTto preserve original fields
Conclusion
The $subtract operator in MongoDB's aggregation pipeline efficiently performs arithmetic subtraction between document fields. Use it within $project to create computed fields based on existing numeric values.
Advertisements
