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
Retrieving a Subset of Fields from MongoDB
To retrieve a subset of fields from MongoDB documents, use field projection in the find() method. You can specify which fields to include (1) or exclude (0) from the results using dot notation for nested fields.
Syntax
db.collection.find(
{ query },
{ "field1": 1, "field2": 0, "nested.field": 1 }
);
Sample Data
db.demo307.insertMany([
{
"ClientId": 101,
"ClientDetails": { "ClientFirstName": "Chris", "Age": 34 },
"ClientCountryName": "US"
},
{
"ClientId": 102,
"ClientDetails": { "ClientFirstName": "David", "Age": 31 },
"ClientCountryName": "UK"
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e4eab88f8647eb59e56203c"),
ObjectId("5e4eab97f8647eb59e56203d")
]
}
Example: Exclude Multiple Fields
Retrieve only the ClientFirstName by excluding other fields ?
db.demo307.find(
{ "ClientDetails.ClientFirstName": "David" },
{
"ClientDetails.Age": 0,
"ClientCountryName": 0,
"ClientId": 0,
"_id": 0
}
);
{ "ClientDetails": { "ClientFirstName": "David" } }
Example: Include Specific Fields
Retrieve only ClientId and ClientFirstName ?
db.demo307.find(
{},
{
"ClientId": 1,
"ClientDetails.ClientFirstName": 1,
"_id": 0
}
);
{ "ClientId": 101, "ClientDetails": { "ClientFirstName": "Chris" } }
{ "ClientId": 102, "ClientDetails": { "ClientFirstName": "David" } }
Key Points
- Use 1 to include fields and 0 to exclude fields in projection.
- Cannot mix inclusion and exclusion (except for
_id). - Use dot notation for nested field projection.
Conclusion
Field projection in MongoDB allows efficient data retrieval by selecting only required fields. Use inclusion (1) or exclusion (0) projections with dot notation for nested documents to optimize query performance and reduce data transfer.
Advertisements
