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
How to project specific fields from a document inside an array in Mongodb?
To project specific fields from a document inside an array in MongoDB, use the positional operator ($) in the projection parameter. This returns only the first matching array element that satisfies the query condition.
Syntax
db.collection.find(
{ "arrayField.subField": "matchValue" },
{ "arrayField.$": 1 }
);
Sample Data
Let us create a collection with sample documents ?
db.projectSpecificFieldDemo.insertMany([
{
"UniqueId": 101,
"StudentDetails": [
{"StudentName": "Chris", "StudentCountryName": "US"},
{"StudentName": "Robert", "StudentCountryName": "UK"}
]
},
{
"UniqueId": 102,
"StudentDetails": [
{"StudentName": "Robert", "StudentCountryName": "UK"},
{"StudentName": "David", "StudentCountryName": "AUS"}
]
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5ca27aeb6304881c5ce84ba2"),
ObjectId("5ca27b106304881c5ce84ba3")
]
}
View All Documents
db.projectSpecificFieldDemo.find().pretty();
{
"_id": ObjectId("5ca27aeb6304881c5ce84ba2"),
"UniqueId": 101,
"StudentDetails": [
{
"StudentName": "Chris",
"StudentCountryName": "US"
},
{
"StudentName": "Robert",
"StudentCountryName": "UK"
}
]
}
{
"_id": ObjectId("5ca27b106304881c5ce84ba3"),
"UniqueId": 102,
"StudentDetails": [
{
"StudentName": "Robert",
"StudentCountryName": "UK"
},
{
"StudentName": "David",
"StudentCountryName": "AUS"
}
]
}
Example: Project Specific Array Element
Find documents where UniqueId is 101 and StudentName is "Chris", then project only the matching array element ?
db.projectSpecificFieldDemo.find(
{
"UniqueId": 101,
"StudentDetails.StudentName": "Chris"
},
{
"StudentDetails.$": 1
}
).pretty();
{
"_id": ObjectId("5ca27aeb6304881c5ce84ba2"),
"StudentDetails": [
{
"StudentName": "Chris",
"StudentCountryName": "US"
}
]
}
Key Points
- The
$positional operator returns only the first matching array element. - The query condition must include a field from the array to match against.
- Use
"arrayField.$": 1in the projection to limit the array to matched elements only.
Conclusion
The positional operator $ effectively projects specific array elements based on query conditions. It returns only the first matching element, making it useful for filtering large arrays to relevant data.
Advertisements
