How can I rename a field for all documents in MongoDB?


The syntax is as follows to rename a field for all documents. Here, we have used $renameL

db.yourCollectionName.update({}, {$rename:{"yourOldFieldName":"yourNewFieldName"}},
false, true);

To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −

> db.renameFieldDemo.insertOne({"StudentName":"John"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c7ee6c7559dd2396bcfbfbb")
}
> db.renameFieldDemo.insertOne({"StudentName":"Carol"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c7ee6cb559dd2396bcfbfbc")
}
> db.renameFieldDemo.insertOne({"StudentName":"Bob"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c7ee6cf559dd2396bcfbfbd")
}
> db.renameFieldDemo.insertOne({"StudentName":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c7ee6d3559dd2396bcfbfbe")
}
> db.renameFieldDemo.insertOne({"StudentName":"Maxwell"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c7ee6d8559dd2396bcfbfbf")
}

Display all documents from a collection with the help of find() method. The query is as follows −

> db.renameFieldDemo.find().pretty();

The following is the output −

{ "_id" : ObjectId("5c7ee6c7559dd2396bcfbfbb"), "StudentName" : "John" }
{ "_id" : ObjectId("5c7ee6cb559dd2396bcfbfbc"), "StudentName" : "Carol" }
{ "_id" : ObjectId("5c7ee6cf559dd2396bcfbfbd"), "StudentName" : "Bob" }
{ "_id" : ObjectId("5c7ee6d3559dd2396bcfbfbe"), "StudentName" : "David" }
{ "_id" : ObjectId("5c7ee6d8559dd2396bcfbfbf"), "StudentName" : "Maxwell" }

Here is the query to rename field “StudentName” to “StudentFirstName” for all documents −

> db.renameFieldDemo.update({}, {$rename:{"StudentName":"StudentFirstName"}}, false,
true);
WriteResult({ "nMatched" : 5, "nUpserted" : 0, "nModified" : 5 })

Let us check all the documents from a collection. The query is as follows

> db.renameFieldDemo.find().pretty();

The following is the output −

{ "_id" : ObjectId("5c7ee6c7559dd2396bcfbfbb"), "StudentFirstName" : "John" }
{
   "_id" : ObjectId("5c7ee6cb559dd2396bcfbfbc"),
   "StudentFirstName" : "Carol"
}
{ "_id" : ObjectId("5c7ee6cf559dd2396bcfbfbd"), "StudentFirstName" : "Bob" }
{
   "_id" : ObjectId("5c7ee6d3559dd2396bcfbfbe"),
   "StudentFirstName" : "David"
}
{
   "_id" : ObjectId("5c7ee6d8559dd2396bcfbfbf"),
   "StudentFirstName" : "Maxwell"
}

Look at the sample output, “StudentName” has been renamed to “StudentFirstName”.

Updated on: 30-Jul-2019

218 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements