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 find and return subdocument with criteria?
To find and return subdocuments that match specific criteria in MongoDB, use the aggregation pipeline with $match to filter documents and $filter to return only matching subdocuments from arrays.
Syntax
db.collection.aggregate([
{ $match: { "fieldName": "value" } },
{
$addFields: {
"arrayField": {
$filter: {
input: "$arrayField",
cond: { $eq: ["$$this.subField", "criteria"] }
}
}
}
}
])
Sample Data
db.demo345.insertOne({
"UserName": "Robert",
"UserDetails": [
{
"isMarried": false,
"CountryName": "US"
},
{
"isMarried": true,
"CountryName": "UK"
},
{
"isMarried": false,
"CountryName": "AUS"
}
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5e5404fdf8647eb59e5620ac")
}
Display all documents from the collection ?
db.demo345.find();
{
"_id": ObjectId("5e5404fdf8647eb59e5620ac"),
"UserName": "Robert",
"UserDetails": [
{ "isMarried": false, "CountryName": "US" },
{ "isMarried": true, "CountryName": "UK" },
{ "isMarried": false, "CountryName": "AUS" }
]
}
Example: Return Subdocuments with Criteria
Find and return only subdocuments where isMarried is true ?
db.demo345.aggregate([
{
$match: { UserName: "Robert" }
},
{
$addFields: {
UserDetails: {
$filter: {
input: "$UserDetails",
cond: {
$eq: ["$$this.isMarried", true]
}
}
}
}
}
]);
{
"_id": ObjectId("5e5404fdf8647eb59e5620ac"),
"UserName": "Robert",
"UserDetails": [
{ "isMarried": true, "CountryName": "UK" }
]
}
Key Points
-
$matchfilters the parent documents first -
$filterreturns only array elements that match the condition -
$$thisrefers to each element in the input array -
$addFieldsreplaces the original array with the filtered results
Conclusion
Use MongoDB's aggregation pipeline with $filter to return specific subdocuments based on criteria. This approach efficiently filters nested arrays while preserving the document structure.
Advertisements
