Is it possible to rename _id field after MongoDB group aggregation?

Yes, it is possible to rename the _id field after MongoDB group aggregation using the $project stage. This technique allows you to map the _id field to a new field name while excluding the original _id from the output.

Syntax

db.collection.aggregate([
    {
        $project: {
            _id: 0,
            newFieldName: "$_id",
            otherFields: 1
        }
    }
]);

Sample Data

db.renameIdDemo.insertMany([
    {"StudentName": "Chris"},
    {"StudentName": "Robert"},
    {"StudentName": "David"}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5c9a1760353decbc2fc927c5"),
        ObjectId("5c9a1765353decbc2fc927c6"),
        ObjectId("5c9a176b353decbc2fc927c7")
    ]
}

Display all documents from the collection ?

db.renameIdDemo.find();
{ "_id" : ObjectId("5c9a1760353decbc2fc927c5"), "StudentName" : "Chris" }
{ "_id" : ObjectId("5c9a1765353decbc2fc927c6"), "StudentName" : "Robert" }
{ "_id" : ObjectId("5c9a176b353decbc2fc927c7"), "StudentName" : "David" }

Example: Rename _id to mainId

db.renameIdDemo.aggregate([
    {
        $project: {
            _id: 0,
            mainId: "$_id",
            StudentName: 1
        }
    }
]);
{ "mainId" : ObjectId("5c9a1760353decbc2fc927c5"), "StudentName" : "Chris" }
{ "mainId" : ObjectId("5c9a1765353decbc2fc927c6"), "StudentName" : "Robert" }
{ "mainId" : ObjectId("5c9a176b353decbc2fc927c7"), "StudentName" : "David" }

Key Points

  • Set _id: 0 to exclude the original _id field from output
  • Use "$_id" syntax to reference the original _id value
  • Include other fields using fieldName: 1 to preserve them

Conclusion

Renaming the _id field in MongoDB aggregation is straightforward using $project. Simply exclude the original _id and map its value to a new field name using the "$_id" reference syntax.

Updated on: 2026-03-15T00:29:22+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements