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 aggregation to fetch documents with specific field value?
To fetch documents with a specific field value using MongoDB aggregation, use the aggregate() method with the $match stage to filter documents based on field criteria.
Syntax
db.collection.aggregate([
{ $unwind: "$arrayField" },
{ $match: { "arrayField.fieldName": value } },
{ $project: { _id: 0 } }
]);
Sample Data
db.demo685.insertOne({
"details": [
{
"Name": "Chris",
"Age": 21
},
{
"Name": "David",
"Age": 23
},
{
"Name": "Bob",
"Age": 21
}
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5ea54f6fa7e81adc6a0b395b")
}
Display all documents from the collection:
db.demo685.find();
{
"_id": ObjectId("5ea54f6fa7e81adc6a0b395b"),
"details": [
{ "Name": "Chris", "Age": 21 },
{ "Name": "David", "Age": 23 },
{ "Name": "Bob", "Age": 21 }
]
}
Example: Fetch Documents with Age = 21
db.demo685.aggregate([
{ $unwind: "$details" },
{ $match: { "details.Age": 21 } },
{ $project: { _id: 0 } }
]);
{ "details": { "Name": "Chris", "Age": 21 } }
{ "details": { "Name": "Bob", "Age": 21 } }
How It Works
-
$unwind− Deconstructs the array field to output separate documents for each element -
$match− Filters documents where the Age field equals 21 -
$project− Excludes the _id field from the output
Conclusion
Use the aggregation pipeline with $unwind and $match stages to filter documents containing array elements with specific field values. This approach effectively extracts matching nested objects from arrays.
Advertisements
