Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Restrict returned data in MongoDB to display only specific values from documents
To restrict returned data in MongoDB, use the projection parameter in the find() method. Use values 1 to include fields and 0 to exclude fields from the query results.
Syntax
db.collection.find(query, projection)
Where:
-
query− Filter criteria (empty {} for all documents) -
projection− Fields to include (1) or exclude (0)
Sample Data
Let us create a collection with documents −
db.demo330.insertMany([
{"Id": 101, "Name": "Chris", "Age": 21},
{"Id": 102, "Name": "Sam", "Age": 24},
{"Id": 103, "Name": "David", "Age": 28},
{"Id": 104, "Name": "Bob", "Age": 23}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e52149ff8647eb59e562081"),
ObjectId("5e5214aaf8647eb59e562082"),
ObjectId("5e5214b3f8647eb59e562083"),
ObjectId("5e5214bdf8647eb59e562084")
]
}
Display all documents from a collection with the help of find() method −
db.demo330.find();
{ "_id" : ObjectId("5e52149ff8647eb59e562081"), "Id" : 101, "Name" : "Chris", "Age" : 21 }
{ "_id" : ObjectId("5e5214aaf8647eb59e562082"), "Id" : 102, "Name" : "Sam", "Age" : 24 }
{ "_id" : ObjectId("5e5214b3f8647eb59e562083"), "Id" : 103, "Name" : "David", "Age" : 28 }
{ "_id" : ObjectId("5e5214bdf8647eb59e562084"), "Id" : 104, "Name" : "Bob", "Age" : 23 }
Example 1: Include Only Specific Fields
Show only the "Name" field by setting it to 1 −
db.demo330.find({}, {Name: 1});
{ "_id" : ObjectId("5e52149ff8647eb59e562081"), "Name" : "Chris" }
{ "_id" : ObjectId("5e5214aaf8647eb59e562082"), "Name" : "Sam" }
{ "_id" : ObjectId("5e5214b3f8647eb59e562083"), "Name" : "David" }
{ "_id" : ObjectId("5e5214bdf8647eb59e562084"), "Name" : "Bob" }
Example 2: Exclude the _id Field
Display only "Name" and "Age" without the default "_id" field −
db.demo330.find({}, {_id: 0, Name: 1, Age: 1});
{ "Name" : "Chris", "Age" : 21 }
{ "Name" : "Sam", "Age" : 24 }
{ "Name" : "David", "Age" : 28 }
{ "Name" : "Bob", "Age" : 23 }
Key Points
- The
_idfield is always included by default unless explicitly excluded with_id: 0. - You cannot mix inclusion (1) and exclusion (0) in the same projection, except for
_id. - Empty projection
{}returns all fields.
Conclusion
MongoDB projection allows you to control which fields are returned in query results. Use 1 to include specific fields and 0 to exclude unwanted data, optimizing query performance and reducing network traffic.
Advertisements
