Set a similar name from another column in MongoDB?

MongoDBDatabaseBig Data Analytics

Simply loop with forEach() and set column value from another column. Let us create a collection with documents −

> db.demo51.insert({"Name1":"Chris","Name":"David","Age":24});
WriteResult({ "nInserted" : 1 })
> db.demo51.insert({"Name1":"Carol","Name":"Mike","Age":22});
WriteResult({ "nInserted" : 1 })
> db.demo51.insert({"Name1":"Sam","Name":"Bob","Age":26});
WriteResult({ "nInserted" : 1 })

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

> db.demo51.find();

This will produce the following output −

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

Following is the query to set a similar name from another column in MongoDB −

> db.demo51.find().forEach( function (d) {
...    d.Name1 = d.Name;
...    db.demo51.save(d);
... });

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

> db.demo51.find();

This will produce the following output −

{ "_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 }
raja
Published on 03-Apr-2020 12:29:38
Advertisements