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
Set a similar name from another column in MongoDB?
To copy the value from one column to another column in MongoDB, use the forEach() method to iterate through documents and update each one individually. This approach is useful when you need to set values from an existing field.
Syntax
db.collection.find().forEach(function(doc) {
doc.targetField = doc.sourceField;
db.collection.save(doc);
});
Sample Data
First, let's create a collection with sample documents ?
db.demo51.insertMany([
{"Name1": "Chris", "Name": "David", "Age": 24},
{"Name1": "Carol", "Name": "Mike", "Age": 22},
{"Name1": "Sam", "Name": "Bob", "Age": 26}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("..."),
ObjectId("..."),
ObjectId("...")
]
}
Display all documents from the collection ?
db.demo51.find();
{ "_id": ObjectId("5e27108ccfb11e5c34d8990d"), "Name1": "Chris", "Name": "David", "Age": 24 }
{ "_id": ObjectId("5e27108dcfb11e5c34d8990e"), "Name1": "Carol", "Name": "Mike", "Age": 22 }
{ "_id": ObjectId("5e27108ecfb11e5c34d8990f"), "Name1": "Sam", "Name": "Bob", "Age": 26 }
Example: Copy Values Using forEach()
Copy the value from Name field to Name1 field for all documents ?
db.demo51.find().forEach(function(doc) {
doc.Name1 = doc.Name;
db.demo51.save(doc);
});
Verify Result
Display the updated documents ?
db.demo51.find();
{ "_id": ObjectId("5e27108ccfb11e5c34d8990d"), "Name1": "David", "Name": "David", "Age": 24 }
{ "_id": ObjectId("5e27108dcfb11e5c34d8990e"), "Name1": "Mike", "Name": "Mike", "Age": 22 }
{ "_id": ObjectId("5e27108ecfb11e5c34d8990f"), "Name1": "Bob", "Name": "Bob", "Age": 26 }
Key Points
-
forEach()iterates through each document returned byfind(). -
save()updates the entire document with the modified values. - This method works well for small collections but can be slow for large datasets.
Conclusion
Use forEach() with save() to copy values between fields in MongoDB documents. This approach provides flexibility for field-level transformations during the update process.
Advertisements
