How to select specific columns in MongoDB query?

To select specific columns in MongoDB, use projection in the find() method. Set fields to 1 to include them or 0 to exclude them. You can hide unwanted columns by setting them to 0, showing only the desired fields.

Syntax

db.collection.find(query, projection)

// Include specific fields
db.collection.find({}, {field1: 1, field2: 1})

// Exclude specific fields  
db.collection.find({}, {field1: 0, field2: 0})

Sample Data

db.demo415.insertMany([
    {"ClientName": "Robert", "ClientCountryName": "US"},
    {"ClientName": "David", "ClientCountryName": "UK"},
    {"ClientName": "Bob", "ClientCountryName": "AUS"}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e72329db912067e57771adc"),
        ObjectId("5e7232acb912067e57771add"),
        ObjectId("5e7232b4b912067e57771ade")
    ]
}

Display all documents from the collection ?

db.demo415.find();
{ "_id": ObjectId("5e72329db912067e57771adc"), "ClientName": "Robert", "ClientCountryName": "US" }
{ "_id": ObjectId("5e7232acb912067e57771add"), "ClientName": "David", "ClientCountryName": "UK" }
{ "_id": ObjectId("5e7232b4b912067e57771ade"), "ClientName": "Bob", "ClientCountryName": "AUS" }

Method 1: Exclude Fields (Hide Unwanted Columns)

To show only ClientCountryName, exclude _id and ClientName ?

db.demo415.find({}, {_id: 0, ClientName: 0});
{ "ClientCountryName": "US" }
{ "ClientCountryName": "UK" }
{ "ClientCountryName": "AUS" }

Method 2: Include Fields (Show Only Desired Columns)

Alternatively, explicitly include only the desired field ?

db.demo415.find({}, {ClientCountryName: 1, _id: 0});
{ "ClientCountryName": "US" }
{ "ClientCountryName": "UK" }
{ "ClientCountryName": "AUS" }

Key Points

  • Use 1 to include fields, 0 to exclude fields
  • Cannot mix inclusion and exclusion except for _id
  • By default, _id is always included unless explicitly set to 0

Conclusion

MongoDB projection allows precise field selection using 1 for inclusion and 0 for exclusion. Use the second parameter of find() to control which columns appear in your query results.

Updated on: 2026-03-15T02:54:40+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements