0
0
MongoDBquery~5 mins

Projection for selecting fields in MongoDB

Choose your learning style9 modes available
Introduction
Projection helps you choose only the information you want from your data, making it easier to see and use.
When you want to see only the names and emails of users, not all their details.
When you need to get just the titles of books from a large collection.
When you want to reduce the amount of data sent over the network by selecting only needed fields.
When you want to hide sensitive information like passwords from query results.
When you want to speed up your app by fetching only important data.
Syntax
MongoDB
db.collection.find(query, { field1: 1, field2: 1, _id: 0 })
Use 1 to include a field and 0 to exclude it.
By default, MongoDB includes the _id field unless you set _id: 0.
Examples
Selects only the name and email fields from all users, hiding the _id.
MongoDB
db.users.find({}, { name: 1, email: 1, _id: 0 })
Finds books by author Alice and shows only their titles and the _id.
MongoDB
db.books.find({ author: "Alice" }, { title: 1, _id: 1 })
Shows product and quantity fields for all orders, hiding the _id.
MongoDB
db.orders.find({}, { _id: 0, product: 1, quantity: 1 })
Sample Program
This inserts three students and then finds all of them, showing only their name and grade fields without the _id.
MongoDB
db.students.insertMany([
  { name: "John", age: 20, grade: "A" },
  { name: "Jane", age: 22, grade: "B" },
  { name: "Mike", age: 21, grade: "A" }
])

// Find all students but show only name and grade, hide _id

db.students.find({}, { name: 1, grade: 1, _id: 0 })
OutputSuccess
Important Notes
You cannot mix including and excluding fields except for the _id field.
If you do not specify projection, MongoDB returns all fields including _id.
Projection helps reduce data size and improve query speed.
Summary
Projection lets you pick only the fields you want to see from your data.
Use 1 to include fields and 0 to exclude them; _id is included by default.
It helps make your queries faster and your results cleaner.