0
0
MongoDBquery~5 mins

Subset pattern for large documents in MongoDB

Choose your learning style9 modes available
Introduction
Sometimes documents in a database are very big. The subset pattern helps us get only the parts we need, making things faster and easier.
When a document has many fields but you only want a few of them.
When you want to reduce the amount of data sent over the network.
When you want to improve the speed of your queries by fetching less data.
When you want to show a summary or preview of a large document.
When working with mobile apps that need less data to save battery and data.
Syntax
MongoDB
db.collection.find(query, {field1: 1, field2: 1, ...})
Use 1 to include a field and 0 to exclude it, but don't mix including and excluding fields except for _id.
By default, MongoDB returns the whole document if no projection is specified.
Examples
Get only the name and email fields from all users.
MongoDB
db.users.find({}, {name: 1, email: 1})
Get title and price of books, but hide the _id field.
MongoDB
db.products.find({category: 'books'}, {title: 1, price: 1, _id: 0})
Get only the items field from orders that are pending.
MongoDB
db.orders.find({status: 'pending'}, {items: 1})
Sample Program
Find books by Jane Austen and show only their title and year without the _id.
MongoDB
db.library.find({author: 'Jane Austen'}, {title: 1, year: 1, _id: 0})
OutputSuccess
Important Notes
The _id field is included by default unless you explicitly exclude it with _id: 0.
Avoid mixing inclusion and exclusion in the same projection except for _id.
Using subset pattern reduces data transfer and speeds up queries.
Summary
Subset pattern helps get only needed parts of large documents.
Use projection in find() to include or exclude fields.
It improves performance and reduces data sent over the network.