To re-map the fields of a MongoDB collection, use update() along with $rename. Let us first create a collection with documents −
> db.demo171.insertOne( { "Name": "Chris", "Details": { "SubjectName": "MySQL", "CountryName": "US" } } ); { "acknowledged" : true, "insertedId" : ObjectId("5e3837 399e4f06af551997e0") }
Display all documents from a collection with the help of find() method −
> db.demo171.find();
This will produce the following output −
{ "_id" : ObjectId("5e3837399e4f06af551997e0"), "Name" : "Chris", "Details" : { "SubjectName" : "MySQL", "CountryName" : "US" } }
Following is the query to re-map the fields of a MongoDB collection −
> db.demo171.update({}, { $rename : { 'Name' : 'StudentName'} }, false, true); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo171.find();
This will produce the following output −
{ "_id" : ObjectId("5e3837399e4f06af551997e0"), "Details" : { "SubjectName" : "MySQL", "CountryName" : "US" }, "StudentName" : "Chris" }