Select special fields rather than all in MongoDB

To select specific fields instead of all fields in MongoDB, use field projection in the find() method. Set unwanted fields to 0 to exclude them, or set wanted fields to 1 to include only those fields.

Syntax

db.collection.find({}, {field1: 0, field2: 0});  // Exclude fields
db.collection.find({}, {field1: 1, field2: 1});  // Include only these fields

Sample Data

db.demo269.insertMany([
    {StudentId: 101, StudentSubject: "MySQL"},
    {StudentId: 102, StudentSubject: "Java"},
    {StudentId: 103, StudentSubject: "MongoDB"},
    {StudentId: 104, StudentSubject: "C"}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e481caa1627c0c63e7dbab4"),
        ObjectId("5e481cb11627c0c63e7dbab5"),
        ObjectId("5e481cb21627c0c63e7dbab6"),
        ObjectId("5e481cb21627c0c63e7dbab7")
    ]
}

View All Documents

db.demo269.find();
{ "_id": ObjectId("5e481caa1627c0c63e7dbab4"), "StudentId": 101, "StudentSubject": "MySQL" }
{ "_id": ObjectId("5e481cb11627c0c63e7dbab5"), "StudentId": 102, "StudentSubject": "Java" }
{ "_id": ObjectId("5e481cb21627c0c63e7dbab6"), "StudentId": 103, "StudentSubject": "MongoDB" }
{ "_id": ObjectId("5e481cb21627c0c63e7dbab7"), "StudentId": 104, "StudentSubject": "C" }

Example: Exclude Specific Fields

To show only the StudentSubject field by excluding StudentId and _id ?

db.demo269.find({}, {"StudentId": 0, "_id": 0});
{ "StudentSubject": "MySQL" }
{ "StudentSubject": "Java" }
{ "StudentSubject": "MongoDB" }
{ "StudentSubject": "C" }

Example: Include Specific Fields

To show only the StudentSubject field using inclusion ?

db.demo269.find({}, {"StudentSubject": 1, "_id": 0});
{ "StudentSubject": "MySQL" }
{ "StudentSubject": "Java" }
{ "StudentSubject": "MongoDB" }
{ "StudentSubject": "C" }

Key Points

  • Use 0 to exclude fields and 1 to include fields in projection.
  • Cannot mix inclusion and exclusion except for _id field.
  • The _id field is included by default unless explicitly excluded with _id: 0.

Conclusion

Field projection in MongoDB allows you to control which fields are returned in query results. Use exclusion (0) or inclusion (1) projection to select specific fields and optimize data transfer.

Updated on: 2026-03-15T02:10:48+05:30

183 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements