0
0
MongodbHow-ToBeginner · 3 min read

How to Exclude Fields in MongoDB Queries

To exclude fields in MongoDB, use a projection in your query by setting the fields you want to exclude to 0. For example, { fieldName: 0 } in the projection will omit that field from the results.
📐

Syntax

In MongoDB, you exclude fields by specifying a projection object in your query. Set the fields you want to exclude to 0. Fields set to 1 are included, and those set to 0 are excluded.

Example syntax:

db.collection.find(query, { fieldToExclude: 0 })

This tells MongoDB to return all fields except fieldToExclude.

mongodb
db.collection.find({}, { password: 0 })
💻

Example

This example shows how to exclude the password field from user documents when querying the users collection.

mongodb
db.users.insertMany([
  { _id: 1, name: "Alice", password: "secret123", email: "alice@example.com" },
  { _id: 2, name: "Bob", password: "pass456", email: "bob@example.com" }
])

// Query excluding the password field
const result = db.users.find({}, { password: 0 }).toArray()
printjson(result)
Output
[ { "_id" : 1, "name" : "Alice", "email" : "alice@example.com" }, { "_id" : 2, "name" : "Bob", "email" : "bob@example.com" } ]
⚠️

Common Pitfalls

One common mistake is mixing inclusion and exclusion in the same projection, which MongoDB does not allow except for the _id field. For example, you cannot exclude password and include name at the same time like { password: 0, name: 1 }.

Also, by default, the _id field is included unless explicitly excluded.

mongodb
/* Wrong: mixing inclusion and exclusion */
db.users.find({}, { password: 0, name: 1 })

/* Correct: exclude password only */
db.users.find({}, { password: 0 })

/* Correct: include only name and email */
db.users.find({}, { name: 1, email: 1, _id: 0 })
📊

Quick Reference

ActionProjection SyntaxDescription
Exclude a field{ fieldName: 0 }Omits the specified field from results
Include specific fields{ field1: 1, field2: 1 }Returns only these fields
Exclude _id field{ _id: 0 }Removes the default _id field from results
Mix inclusion and exclusionNot allowed except for _idCauses error if mixed incorrectly

Key Takeaways

Use projection with 0 to exclude fields in MongoDB queries.
Do not mix inclusion (1) and exclusion (0) in the same projection except for _id.
By default, _id is included unless explicitly excluded.
Projection controls which fields appear in query results to optimize data transfer.