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
Project specific array field in a MongoDB collection?
To project specific fields from an array in MongoDB, use dot notation in the projection document to select only the desired fields from nested array elements. This allows you to return specific fields from array objects while excluding unwanted data.
Syntax
db.collection.find(
{},
{
"fieldName": 1,
"arrayField.nestedField": 1
}
);
Create Sample Data
db.projectionAnElementDemo.insertOne(
{
"CustomerId": 100,
"CustomerDetails": [
{
"CustomerName": "Chris",
"CustomerCountryName": "US"
},
{
"CustomerName": "Robert",
"CustomerCountryName": "UK"
}
]
}
);
{
"acknowledged": true,
"insertedId": ObjectId("5cd31c56b64f4b851c3a13ea")
}
Display All Documents
db.projectionAnElementDemo.find().pretty();
{
"_id": ObjectId("5cd31c56b64f4b851c3a13ea"),
"CustomerId": 100,
"CustomerDetails": [
{
"CustomerName": "Chris",
"CustomerCountryName": "US"
},
{
"CustomerName": "Robert",
"CustomerCountryName": "UK"
}
]
}
Project Specific Array Fields
Project only CustomerId and CustomerName from the array ?
db.projectionAnElementDemo.find(
{},
{
CustomerId: 1,
"CustomerDetails.CustomerName": 1
}
).pretty();
{
"_id": ObjectId("5cd31c56b64f4b851c3a13ea"),
"CustomerId": 100,
"CustomerDetails": [
{
"CustomerName": "Chris"
},
{
"CustomerName": "Robert"
}
]
}
Key Points
- Use dot notation in projection:
"arrayField.nestedField": 1 - The
_idfield is included by default unless explicitly excluded - All array elements are returned but only with projected fields
Conclusion
MongoDB array field projection uses dot notation to select specific nested fields from array elements. This technique efficiently reduces data transfer by returning only the required fields from complex nested documents.
Advertisements
