Creating alias in a MongoDB query?

To create an alias in a MongoDB query, use the aggregation framework with the $project stage. This allows you to rename fields in the output by mapping original field names to new alias names.

Syntax

db.collection.aggregate([
    {
        $project: {
            _id: 1,
            "aliasName": "$originalFieldName"
        }
    }
]);

Sample Data

db.creatingAliasDemo.insertMany([
    {_id: 101, "Name": "John Doe"},
    {_id: 102, "Name": "David Miller"},
    {_id: 103, "Name": "Sam Williams"}
]);
{
    "acknowledged": true,
    "insertedIds": [101, 102, 103]
}

View Original Data

db.creatingAliasDemo.find();
{ "_id": 101, "Name": "John Doe" }
{ "_id": 102, "Name": "David Miller" }
{ "_id": 103, "Name": "Sam Williams" }

Example: Creating Field Alias

Create an alias "FullName" for the "Name" field ?

db.creatingAliasDemo.aggregate([
    {
        $project: {
            _id: 1,
            "FullName": "$Name"
        }
    }
]);
{ "_id": 101, "FullName": "John Doe" }
{ "_id": 102, "FullName": "David Miller" }
{ "_id": 103, "FullName": "Sam Williams" }

Key Points

  • The $project stage reshapes documents by including, excluding, or renaming fields.
  • Use "aliasName": "$originalFieldName" syntax to create field aliases.
  • Set _id: 1 to include the _id field, or _id: 0 to exclude it.

Conclusion

MongoDB's aggregation framework with $project provides a clean way to create field aliases. This approach transforms field names in query results without modifying the original document structure.

Updated on: 2026-03-15T00:47:12+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements