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 would I filter out sub documents in MongoDB?
To filter out sub documents in MongoDB, use the aggregation pipeline with $unwind to deconstruct array elements and $match to apply filtering conditions on the individual sub documents.
Syntax
db.collection.aggregate([
{ $unwind: "$arrayField" },
{ $match: { "arrayField.field": { $operator: value } } }
]);
Sample Data
db.demo662.insertOne({
"details": [
{
"Name": "Chris",
"Marks": 35
},
{
"Name": "Bob",
"Marks": 45
},
{
"Name": "David",
"Marks": 30
}
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5ea1b2be24113ea5458c7d04")
}
Display all documents from the collection ?
db.demo662.find();
{
"_id": ObjectId("5ea1b2be24113ea5458c7d04"),
"details": [
{ "Name": "Chris", "Marks": 35 },
{ "Name": "Bob", "Marks": 45 },
{ "Name": "David", "Marks": 30 }
]
}
Example: Filter Sub Documents with Marks > 40
db.demo662.aggregate([
{ $unwind: "$details" },
{ $match: { "details.Marks": { $gt: 40 } } }
]);
{
"_id": ObjectId("5ea1b2be24113ea5458c7d04"),
"details": { "Name": "Bob", "Marks": 45 }
}
How It Works
-
$unwindcreates separate documents for each array element -
$matchfilters the unwound documents based on specified conditions - Only sub documents meeting the criteria are returned in the final result
Conclusion
Use $unwind followed by $match in the aggregation pipeline to effectively filter sub documents. This approach transforms array elements into individual documents for precise filtering based on nested field values.
Advertisements
