How to copy attributes in MongoDB?


To copy the value of one attribute to another, use $set along with update(). Let us create a collection with documents −

> db.demo55.insertOne({"ShippingDate":'',"date":new ISODate("2019-01-21")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2716dfcfb11e5c34d89915")
}
> db.demo55.insertOne({"ShippingDate":'',"date":new ISODate("2020-05-12")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2716ebcfb11e5c34d89916")
}

Display all documents from a collection with the help of find() method −

> db.demo55.find();

This will produce the following output −

{ "_id" : ObjectId("5e2716dfcfb11e5c34d89915"), "ShippingDate" : "", "date" : ISODate("2019-01-21T00:00:00Z") }
{ "_id" : ObjectId("5e2716ebcfb11e5c34d89916"), "ShippingDate" : "", "date" : ISODate("2020-05-12T00:00:00Z") }

Following is the query to copy attributes in MongoDB −

> db.demo55.find({}).forEach(function(c){
...    db.demo55.update({_id: c._id}, {$set: {ShippingDate:c.date}});
... });

Display all documents from a collection with the help of find() method −

> db.demo55.find();

This will produce the following output −

{ "_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") }

Updated on: 03-Apr-2020

392 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements