MongoDB query to display all the values excluding the id?

To exclude the _id field from MongoDB query results, use the $project operator in an aggregation pipeline. The $project stage allows you to include or exclude fields, suppress the _id field, and rename existing fields.

Syntax

db.collection.aggregate([
    { $project: { _id: 0, field1: 1, field2: 1 } }
]);

Sample Data

db.demo226.insertMany([
    { "Name": "Chris", "Age": 21 },
    { "Name": "Bob", "Age": 20 },
    { "Name": "David", "Age": 22 }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e3f9be803d395bdc2134738"),
        ObjectId("5e3f9bf003d395bdc2134739"),
        ObjectId("5e3f9bf803d395bdc213473a")
    ]
}

Display All Documents (with _id)

db.demo226.find();
{ "_id": ObjectId("5e3f9be803d395bdc2134738"), "Name": "Chris", "Age": 21 }
{ "_id": ObjectId("5e3f9bf003d395bdc2134739"), "Name": "Bob", "Age": 20 }
{ "_id": ObjectId("5e3f9bf803d395bdc213473a"), "Name": "David", "Age": 22 }

Method 1: Exclude _id Using $project

db.demo226.aggregate([
    { $project: {
        _id: false,
        "StudentFirstName": "$Name",
        "StudentAge": "$Age"
    }}
]);
{ "StudentFirstName": "Chris", "StudentAge": 21 }
{ "StudentFirstName": "Bob", "StudentAge": 20 }
{ "StudentFirstName": "David", "StudentAge": 22 }

Method 2: Using find() with Projection

db.demo226.find({}, { _id: 0, Name: 1, Age: 1 });
{ "Name": "Chris", "Age": 21 }
{ "Name": "Bob", "Age": 20 }
{ "Name": "David", "Age": 22 }

Key Points

  • Set _id: false or _id: 0 to exclude the _id field from results.
  • Use $project in aggregation for field renaming and transformation.
  • Use find() projection for simple field inclusion/exclusion.

Conclusion

Use $project with _id: false in aggregation pipelines or projection parameters in find() to exclude the _id field from MongoDB query results. The aggregation approach also allows field renaming and transformation.

Updated on: 2026-03-15T02:00:03+05:30

627 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements