Particular field as result in MongoDB?

To get particular fields as a result in MongoDB, use field projection with the find() or findOne() methods. This allows you to return only specific fields instead of entire documents.

Syntax

db.collection.findOne(
    { "fieldName": "value" },
    { "fieldToInclude": 1, "_id": 0 }
);

Sample Data

db.particularFieldDemo.insertMany([
    {
        "EmployeeName": "John Smith",
        "EmployeeAge": 26,
        "EmployeeTechnology": "MongoDB"
    },
    {
        "EmployeeName": "Chris Brown",
        "EmployeeAge": 28,
        "EmployeeTechnology": "Java"
    },
    {
        "EmployeeName": "David Miller",
        "EmployeeAge": 30,
        "EmployeeTechnology": "MySQL"
    },
    {
        "EmployeeName": "John Doe",
        "EmployeeAge": 31,
        "EmployeeTechnology": "C++"
    }
]);

Example 1: Find Specific Field Only

Retrieve only the EmployeeName for an employee with Java technology ?

db.particularFieldDemo.findOne(
    { "EmployeeTechnology": "Java" },
    { "EmployeeName": 1 }
);
{
    "_id": ObjectId("5cd9b4d2b50a6c6dd317ada3"),
    "EmployeeName": "Chris Brown"
}

Example 2: Exclude _id Field

Get only the name without the _id field ?

db.particularFieldDemo.findOne(
    { "EmployeeTechnology": "Java" },
    { "EmployeeName": 1, "_id": 0 }
);
{
    "EmployeeName": "Chris Brown"
}

Example 3: Multiple Fields

Retrieve both name and age for a specific employee ?

db.particularFieldDemo.findOne(
    { "EmployeeTechnology": "MongoDB" },
    { "EmployeeName": 1, "EmployeeAge": 1, "_id": 0 }
);
{
    "EmployeeName": "John Smith",
    "EmployeeAge": 26
}

Key Points

  • Use 1 to include a field and 0 to exclude it
  • The _id field is included by default unless explicitly excluded with "_id": 0
  • Both find() and findOne() support field projection

Conclusion

Field projection in MongoDB allows you to retrieve only the required fields, reducing network traffic and improving query performance. Use the second parameter in find() or findOne() to specify which fields to include or exclude.

Updated on: 2026-03-15T01:22:48+05:30

174 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements