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 copy attributes in MongoDB?
To copy the value of one attribute to another in MongoDB, use $set with forEach() to iterate through documents and update each one by copying the source field value to the target field.
Syntax
db.collection.find({}).forEach(function(doc) {
db.collection.update(
{ _id: doc._id },
{ $set: { targetField: doc.sourceField } }
);
});
Sample Data
db.demo55.insertMany([
{ "ShippingDate": "", "date": new ISODate("2019-01-21") },
{ "ShippingDate": "", "date": new ISODate("2020-05-12") }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e2716dfcfb11e5c34d89915"),
ObjectId("5e2716ebcfb11e5c34d89916")
]
}
Display all documents from the collection ?
db.demo55.find();
{ "_id": ObjectId("5e2716dfcfb11e5c34d89915"), "ShippingDate": "", "date": ISODate("2019-01-21T00:00:00Z") }
{ "_id": ObjectId("5e2716ebcfb11e5c34d89916"), "ShippingDate": "", "date": ISODate("2020-05-12T00:00:00Z") }
Example: Copy date to ShippingDate
Copy the date field value to the ShippingDate field for all documents ?
db.demo55.find({}).forEach(function(doc) {
db.demo55.update(
{ _id: doc._id },
{ $set: { ShippingDate: doc.date } }
);
});
Verify Result
db.demo55.find();
{ "_id": ObjectId("5e2716dfcfb11e5c34d89915"), "ShippingDate": ISODate("2019-01-21T00:00:00Z"), "date": ISODate("2019-01-21T00:00:00Z") }
{ "_id": ObjectId("5e2716ebcfb11e5c34d89916"), "ShippingDate": ISODate("2020-05-12T00:00:00Z"), "date": ISODate("2020-05-12T00:00:00Z") }
Key Points
-
forEach()iterates through each document in the collection. -
$setupdates the target field with the source field value. - Use
doc._idto identify each document for individual updates.
Conclusion
The forEach() method combined with $set allows you to copy attribute values between fields across all documents in a collection. This approach ensures each document is updated individually with its own field values.
Advertisements
