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
Update MongoDB variable value with variable itself?
To update a MongoDB field value using its current value as part of the new value, use the $set operator with string concatenation or the $concat aggregation operator within an update pipeline.
Syntax
// Using aggregation pipeline (recommended)
db.collection.updateMany(
{},
[{ $set: { fieldName: { $concat: ["$fieldName", " additional text"] } } }]
);
// Using $set with literal string (replaces with literal text)
db.collection.update(
{},
{ $set: { fieldName: "fieldName additional text" } }
);
Sample Data
db.demo256.insertMany([
{ "Name": "Chris" },
{ "Name": "Bob" },
{ "Name": "David" }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e47a3e91627c0c63e7dba8b"),
ObjectId("5e47a3ea1627c0c63e7dba8c"),
ObjectId("5e47a3eb1627c0c63e7dba8d")
]
}
Method 1: Using Aggregation Pipeline (Recommended)
Update all documents to append " is a student" to existing Name values ?
db.demo256.updateMany(
{},
[{ $set: { "Name": { $concat: ["$Name", " is a student"] } } }]
);
{ "acknowledged": true, "matchedCount": 3, "modifiedCount": 3 }
Method 2: Using $set with Literal String
This approach replaces the field with a literal string value ?
db.demo256.update(
{},
{ $set: { "Name": "Name is a student" } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Results
db.demo256.find();
{ "_id": ObjectId("5e47a3e91627c0c63e7dba8b"), "Name": "Chris is a student" }
{ "_id": ObjectId("5e47a3ea1627c0c63e7dba8c"), "Name": "Bob is a student" }
{ "_id": ObjectId("5e47a3eb1627c0c63e7dba8d"), "Name": "David is a student" }
Key Differences
-
Aggregation pipeline with
$concatuses the actual field value ($Name) - Literal $set replaces with the string "Name" (not the field value)
-
updateMany()affects all matching documents,update()affects only the first
Conclusion
Use aggregation pipelines with $concat to update fields using their current values. The $set operator with literal strings only replaces with fixed text, not the actual field content.
Advertisements
