Return a specific field in MongoDB?

To return a specific field in MongoDB, use the projection parameter in the find() method. Set the desired field to 1 to include it and _id to 0 to exclude the default ID field.

Syntax

db.collection.find({}, {fieldName: 1, _id: 0});

Sample Data

db.specificFieldDemo.insertMany([
    {"FirstName": "John", "LastName": "Doe"},
    {"FirstName": "John", "LastName": "Smith"},
    {"FirstName": "David", "LastName": "Miller"},
    {"FirstName": "Sam", "LastName": "Williams"}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5cb8019a623186894665ae31"),
        ObjectId("5cb801ab623186894665ae32"),
        ObjectId("5cb801b3623186894665ae33"),
        ObjectId("5cb801bf623186894665ae34")
    ]
}

Example 1: Display All Documents

db.specificFieldDemo.find().pretty();
{
    "_id": ObjectId("5cb8019a623186894665ae31"),
    "FirstName": "John",
    "LastName": "Doe"
}
{
    "_id": ObjectId("5cb801ab623186894665ae32"),
    "FirstName": "John",
    "LastName": "Smith"
}
{
    "_id": ObjectId("5cb801b3623186894665ae33"),
    "FirstName": "David",
    "LastName": "Miller"
}
{
    "_id": ObjectId("5cb801bf623186894665ae34"),
    "FirstName": "Sam",
    "LastName": "Williams"
}

Example 2: Return Only LastName Field

db.specificFieldDemo.find({}, {_id: 0, LastName: 1});
{"LastName": "Doe"}
{"LastName": "Smith"}
{"LastName": "Miller"}
{"LastName": "Williams"}

Key Points

  • Use 1 to include a field and 0 to exclude it in the projection parameter.
  • The _id field is included by default ? set _id: 0 to exclude it.
  • You can return multiple specific fields by setting each to 1.

Conclusion

MongoDB's projection parameter in find() allows selective field retrieval. Use {fieldName: 1, _id: 0} to return only the desired field without the default ID.

Updated on: 2026-03-15T00:45:53+05:30

453 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements