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
Update MongoDB field using value of another field?
In MongoDB, you can update a field using the value of another field in the same document. There are two main approaches − using the aggregation pipeline with $set (MongoDB 4.2+) or using $addFields with $out for writing results to a collection.
Method 1: Update with Aggregation Pipeline (MongoDB 4.2+)
Use updateMany() with an aggregation pipeline to set a field based on other fields ?
// Create sample data
db.studentInformation.insertOne({
"StudentFirstName": "Carol",
"StudentLastName": "Taylor"
});
// Update: create FullName from FirstName + LastName
db.studentInformation.updateMany(
{},
[{ $set: { "FullName": { $concat: ["$StudentFirstName", " ", "$StudentLastName"] } } }]
);
// Verify
db.studentInformation.find().pretty();
{
"_id": ObjectId("..."),
"StudentFirstName": "Carol",
"StudentLastName": "Taylor",
"FullName": "Carol Taylor"
}
Method 2: Using $addFields with $out
$addFields creates a computed field, and $out writes the result to a collection ?
db.studentInformation.aggregate([
{
$addFields: {
"FullName": { $concat: ["$StudentFirstName", " ", "$StudentLastName"] }
}
},
{ $out: "studentInformation" }
]);
// Verify
db.studentInformation.find().pretty();
{
"_id": ObjectId("..."),
"StudentFirstName": "Carol",
"StudentLastName": "Taylor",
"FullName": "Carol Taylor"
}
Note: $out replaces the entire target collection. Use Method 1 (updateMany) for in-place updates without replacing the collection.
More Examples
Other common operations using one field's value to update another ?
// Copy one field to another
db.products.updateMany({}, [{ $set: { "backup_price": "$price" } }]);
// Math operations between fields
db.orders.updateMany({}, [{ $set: { "total": { $multiply: ["$quantity", "$unit_price"] } } }]);
// Conditional update
db.users.updateMany({}, [{
$set: {
"status": { $cond: { if: { $gte: ["$age", 18] }, then: "adult", else: "minor" } }
}
}]);
Conclusion
Use updateMany() with an aggregation pipeline (MongoDB 4.2+) to update fields using values from other fields in the same document. Common expressions include $concat, $multiply, and $cond for string, math, and conditional operations respectively.
