0
0
MongoDBquery~5 mins

Projection for reducing data transfer in MongoDB

Choose your learning style9 modes available
Introduction
Projection helps you get only the data you need from a database, making data transfer faster and lighter.
When you want to see only specific details about users, like their names but not their passwords.
When you need to display a list of products with just their names and prices, not all details.
When you want to reduce the amount of data sent over the network to improve app speed.
When you want to save memory by fetching only necessary fields from large documents.
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 explicitly exclude it.
Examples
Get only the name and email fields from all users, excluding the _id.
MongoDB
db.users.find({}, { name: 1, email: 1, _id: 0 })
Get the title and price of products in the 'books' category, _id included by default.
MongoDB
db.products.find({ category: 'books' }, { title: 1, price: 1 })
Get only the orderDate field from all orders, excluding the _id.
MongoDB
db.orders.find({}, { _id: 0, orderDate: 1 })
Sample Program
This inserts three employees and then fetches only their names and departments without the _id field.
MongoDB
db.employees.insertMany([
  { name: 'Alice', age: 30, department: 'HR' },
  { name: 'Bob', age: 25, department: 'Sales' },
  { name: 'Carol', age: 27, department: 'HR' }
])

// Find all employees but only show their name and department, exclude _id

db.employees.find({}, { name: 1, department: 1, _id: 0 })
OutputSuccess
Important Notes
Projection only controls which fields are returned, not which documents are selected.
You cannot mix including and excluding fields in the same projection except for the _id field.
Always exclude _id if you don't want it, because it is included by default.
Summary
Projection lets you pick only the fields you want from documents.
Use 1 to include fields and 0 to exclude them, except _id which is included by default.
Projection helps reduce data size and speeds up data transfer.