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
MongoDB query to return specific fields from an array?
To return specific fields from an array in MongoDB, use the aggregation framework with $project stage. You can extract individual array elements or transform array data into specific output formats.
Syntax
db.collection.aggregate([
{
$project: {
fieldName: { $arrayElemAt: ["$arrayField.subField", index] },
"arrayField.subField": 1
}
}
]);
Sample Data
db.returnSpecificFieldDemo.insertOne({
"StudentId": 1,
"StudentDetails": [
{
"StudentName": "Larry",
"StudentAge": 21,
"StudentCountryName": "US"
},
{
"StudentName": "Chris",
"StudentAge": 23,
"StudentCountryName": "AUS"
}
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5ce23d3236e8b255a5eee943")
}
Example 1: Extract Specific Array Element
Return StudentId and the country name from the second student (index 1) ?
db.returnSpecificFieldDemo.aggregate([
{
$project: {
_id: 0,
StudentId: "$StudentId",
StudentCountryName: {
$arrayElemAt: ["$StudentDetails.StudentCountryName", 1]
}
}
}
]);
{ "StudentId": 1, "StudentCountryName": "AUS" }
Example 2: Return Multiple Array Fields
Project only StudentName and StudentAge from all array elements ?
db.returnSpecificFieldDemo.aggregate([
{
$project: {
_id: 0,
StudentId: 1,
"StudentDetails.StudentName": 1,
"StudentDetails.StudentAge": 1
}
}
]);
{
"StudentId": 1,
"StudentDetails": [
{ "StudentName": "Larry", "StudentAge": 21 },
{ "StudentName": "Chris", "StudentAge": 23 }
]
}
Key Points
-
$arrayElemAtextracts a single element from an array by index position. - Dot notation like
"arrayField.subField"projects specific fields from all array elements. - Use
_id: 0to exclude the default ObjectId from results.
Conclusion
MongoDB's aggregation $project stage allows precise field selection from arrays. Use $arrayElemAt for single elements or dot notation for filtering fields across all array elements.
Advertisements
