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
MongoDB - How to get the sum of two columns and save it to another column?
To get the sum of two columns and save it to another column in MongoDB, use the $add operator within an aggregation pipeline with the $project stage.
Syntax
db.collection.aggregate([
{
$project: {
field1: "$field1",
field2: "$field2",
sumField: { $add: ["$field1", "$field2"] }
}
}
]);
Sample Data
Let us create a collection with sample documents ?
db.demo291.insertOne({"Value1": 10, "Value2": 50});
{
"acknowledged": true,
"insertedId": ObjectId("5e4c0e1e5d93261e4bc9ea2f")
}
Display all documents from the collection ?
db.demo291.find();
{ "_id": ObjectId("5e4c0e1e5d93261e4bc9ea2f"), "Value1": 10, "Value2": 50 }
Example: Sum Two Columns
Get the sum of Value1 and Value2, and save it to a new column "Value3" ?
db.demo291.aggregate([
{
$project: {
"Value1": "$Value1",
"Value2": "$Value2",
"Value3": { $add: ["$Value1", "$Value2"] }
}
}
]);
{ "_id": ObjectId("5e4c0e1e5d93261e4bc9ea2f"), "Value1": 10, "Value2": 50, "Value3": 60 }
Key Points
- The
$addoperator takes an array of numeric fields to sum - Use
$projectto include original fields and the computed sum - Field references require the
$prefix (e.g.,"$Value1")
Conclusion
Use MongoDB's $add operator within an aggregation pipeline to sum multiple columns and project the result as a new field. This approach allows you to perform calculations while preserving original data.
Advertisements
