How to hide _id from Aggregation?

To hide the _id field from aggregation results in MongoDB, use the $project stage with _id: 0 to exclude it while specifying other fields to include.

Syntax

db.collectionName.aggregate([
    {
        $project: {
            _id: 0,
            fieldName1: 1,
            fieldName2: 1
        }
    }
])

Sample Data

Let's create a collection with sample documents ?

db.hideidDemo.insertMany([
    {"UserName": "Larry", "UserAge": 23, "UserCountryName": "US"},
    {"UserName": "Chris", "UserAge": 21, "UserCountryName": "AUS"},
    {"UserName": "Robert", "UserAge": 26, "UserCountryName": "UK"}
])
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5c92b02336de59bd9de06392"),
        ObjectId("5c92b03036de59bd9de06393"),
        ObjectId("5c92b04036de59bd9de06394")
    ]
}

View all documents to see the data structure ?

db.hideidDemo.find().pretty()
{
    "_id": ObjectId("5c92b02336de59bd9de06392"),
    "UserName": "Larry",
    "UserAge": 23,
    "UserCountryName": "US"
}
{
    "_id": ObjectId("5c92b03036de59bd9de06393"),
    "UserName": "Chris",
    "UserAge": 21,
    "UserCountryName": "AUS"
}
{
    "_id": ObjectId("5c92b04036de59bd9de06394"),
    "UserName": "Robert",
    "UserAge": 26,
    "UserCountryName": "UK"
}

Example: Hide _id and Select Specific Fields

Use aggregation with $project to exclude _id and include only UserName and UserCountryName ?

db.hideidDemo.aggregate([
    {
        $project: {
            _id: 0,
            UserName: 1,
            UserCountryName: 1
        }
    }
])
{"UserName": "Larry", "UserCountryName": "US"}
{"UserName": "Chris", "UserCountryName": "AUS"}
{"UserName": "Robert", "UserCountryName": "UK"}

Key Points

  • Set _id: 0 in the $project stage to exclude the _id field
  • Use fieldName: 1 to explicitly include other fields
  • By default, _id is always included unless explicitly excluded

Conclusion

The $project stage with _id: 0 effectively hides the _id field from aggregation output. This approach gives you clean results containing only the fields you need for your analysis.

Updated on: 2026-03-15T00:20:00+05:30

620 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements