How can I change the field name in MongoDB?

To change the field name in MongoDB, use the $project operator in an aggregation pipeline. This creates a projection with the new field name while mapping the value from the original field.

Syntax

db.collection.aggregate([
    { $project: { "newFieldName": "$originalFieldName" } }
]);

Create Sample Data

Let us create a collection with documents ?

db.demo517.insertMany([
    { "Name": "Chris Brown" },
    { "Name": "David Miller" },
    { "Name": "John Doe" }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e88a2a2987b6e0e9d18f595"),
        ObjectId("5e88a2ab987b6e0e9d18f596"),
        ObjectId("5e88a2b1987b6e0e9d18f597")
    ]
}

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

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

Example: Change Field Name from "Name" to "FullName"

Following is the query to change the field name ?

db.demo517.aggregate([
    { $project: { "FullName": "$Name" } }
]);
{ "_id": ObjectId("5e88a2a2987b6e0e9d18f595"), "FullName": "Chris Brown" }
{ "_id": ObjectId("5e88a2ab987b6e0e9d18f596"), "FullName": "David Miller" }
{ "_id": ObjectId("5e88a2b1987b6e0e9d18f597"), "FullName": "John Doe" }

Key Points

  • The $project operator creates a new field with the desired name.
  • Use "$fieldName" syntax to reference the original field value.
  • This operation only changes the field name in the query output, not in the stored documents.

Conclusion

Use $project in aggregation pipelines to rename fields in query results. The original field names remain unchanged in the database unless you update the documents permanently.

Updated on: 2026-03-15T03:21:56+05:30

281 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements