0
0
MongoDBquery~5 mins

Excluding fields from results in MongoDB

Choose your learning style9 modes available
Introduction

Sometimes you want to see only some parts of your data and hide others. Excluding fields helps you get just what you need.

When you want to hide sensitive information like passwords from query results.
When you only need a few fields and want to ignore the rest to save data transfer.
When you want to simplify the output to focus on important details.
When you want to improve performance by not loading unnecessary data.
Syntax
MongoDB
db.collection.find(query, { fieldToExclude: 0 })

Use 0 to exclude a field and 1 to include a field.

You cannot mix including and excluding fields except for the _id field.

Examples
Find all users but exclude the password field from the results.
MongoDB
db.users.find({}, { password: 0 })
Find all products but exclude both description and reviews fields.
MongoDB
db.products.find({}, { description: 0, reviews: 0 })
Find all orders but exclude the _id and creditCardNumber fields.
MongoDB
db.orders.find({}, { _id: 0, creditCardNumber: 0 })
Sample Program

This example inserts three employees and then finds all employees but excludes the salary field from the results.

MongoDB
db.employees.insertMany([
  { name: "Alice", age: 30, salary: 5000 },
  { name: "Bob", age: 25, salary: 4000 },
  { name: "Charlie", age: 35, salary: 6000 }
])

db.employees.find({}, { salary: 0 })
OutputSuccess
Important Notes

The _id field is included by default unless you explicitly exclude it with _id: 0.

Excluding fields can help reduce the amount of data sent over the network.

Summary

Use 0 in the projection to exclude fields from query results.

You cannot mix excluding and including fields except for _id.

Excluding fields helps focus on important data and improves performance.