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
Find by _id on an array of objects in MongoDB database?
To find by _id on an array of objects in MongoDB, use the aggregation framework with $unwind and $match operators. This approach is more effective than using find() when working with nested array elements.
Syntax
db.collection.aggregate([
{ $unwind: "$arrayField" },
{ $match: { "arrayField.field": "value" } }
]);
Sample Data
db.demo414.insertOne({
"_id": "110",
"details": [
{
"StudentName": "John",
"StudentMarks": 56
},
{
"StudentName": "Robert",
"StudentMarks": 98
}
]
});
{ "acknowledged": true, "insertedId": "110" }
Display Sample Data
db.demo414.find();
{
"_id": "110",
"details": [
{ "StudentName": "John", "StudentMarks": 56 },
{ "StudentName": "Robert", "StudentMarks": 98 }
]
}
Example: Find Specific Array Element
Find the document with a student having marks of 56 ?
db.demo414.aggregate([
{ $unwind: "$details" },
{ $match: { "details.StudentMarks": 56 } }
]);
{
"_id": "110",
"details": { "StudentName": "John", "StudentMarks": 56 }
}
How It Works
-
$unwinddeconstructs the array field, creating separate documents for each array element -
$matchfilters documents based on the specified condition within the unwound array - The result returns the parent document with only the matching array element
Conclusion
Use MongoDB's aggregation pipeline with $unwind and $match to effectively query array elements by their fields. This method provides precise filtering within nested array structures.
Advertisements
