Renaming column name in a MongoDB collection?


To rename column name in a collection, you can use $rename operator. Following is the syntax

db.yourCollectionName.update({}, {$rename: {'yourOldColumName': 'yourNewColumnName'}}, false, true);

Let us first create a collection with documents:

> db.renamingColumnNameDemo.insertOne({"StudentName":"Larry","Age":23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9ee2c6d628fa4220163b9a")
}
> db.renamingColumnNameDemo.insertOne({"StudentName":"Sam","Age":26});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9ee2d0d628fa4220163b9b")
}
> db.renamingColumnNameDemo.insertOne({"StudentName":"Robert","Age":27});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9ee2dbd628fa4220163b9c")
}

Following is the query to display all documents from a collection with the help of find() method

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

This will produce the following output

{
   "_id" : ObjectId("5c9ee2c6d628fa4220163b9a"),
   "StudentName" : "Larry",
   "Age" : 23
}
{
   "_id" : ObjectId("5c9ee2d0d628fa4220163b9b"),
   "StudentName" : "Sam",
   "Age" : 26
}
{
   "_id" : ObjectId("5c9ee2dbd628fa4220163b9c"),
   "StudentName" : "Robert",
   "Age" : 27
}

Following is the query to rename column name in a MongoDB collection

> db.renamingColumnNameDemo.update({}, {$rename: {'Age': 'StudentAge'}}, false, true);
WriteResult({ "nMatched" : 3, "nUpserted" : 0, "nModified" : 3 })

Now check the column Age has been renamed with “StudentAge”

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

This will produce the following output

{
   "_id" : ObjectId("5c9ee2c6d628fa4220163b9a"),
   "StudentName" : "Larry",
   "StudentAge" : 23
}
{
   "_id" : ObjectId("5c9ee2d0d628fa4220163b9b"),
   "StudentName" : "Sam",
   "StudentAge" : 26
}
{
   "_id" : ObjectId("5c9ee2dbd628fa4220163b9c"),
   "StudentName" : "Robert",
   "StudentAge" : 27
}

Updated on: 30-Jul-2019

493 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements