How can I change the field name in MongoDB?



To change the field name, use the $project. Let us create a collection with documents −

> db.demo517.insertOne({"Name":"Chris Brown"});{    "acknowledged" : true,    "insertedId" : ObjectId("5e88a2a2987b6e0e9d18f595") } > db.demo517.insertOne({"Name":"David Miller"});{    "acknowledged" : true,    "insertedId" : ObjectId("5e88a2ab987b6e0e9d18f596") } > db.demo517.insertOne({"Name":"John Doe"});{    "acknowledged" : true,    "insertedId" : ObjectId("5e88a2b1987b6e0e9d18f597") }

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

> db.demo517.find();

This will produce the following output −

{ "_id" : ObjectId("5e88a2a2987b6e0e9d18f595"), "Name" : "Chris Brown" } { "_id" : ObjectId("5e88a2ab987b6e0e9d18f596"), "Name" : "David Miller" } { "_id" : ObjectId("5e88a2b1987b6e0e9d18f597"), "Name" : "John Doe" }

Following is the query to change the field name −

> db.demo517.aggregate([{$project:{FullName:"$Name"}}]);

This will produce the following output −

{ "_id" : ObjectId("5e88a2a2987b6e0e9d18f595"), "FullName" : "Chris Brown" } { "_id" : ObjectId("5e88a2ab987b6e0e9d18f596"), "FullName" : "David Miller" } { "_id" : ObjectId("5e88a2b1987b6e0e9d18f597"), "FullName" : "John Doe" }
Updated on: 2020-05-13T07:08:15+05:30

232 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements