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 add matched key to list after query?
To add matched elements to a list after querying in MongoDB, use the $filter operator within an aggregation pipeline. This allows you to filter array elements based on specific conditions and return only the matching elements.
Syntax
db.collection.aggregate([
{
$addFields: {
arrayField: {
$filter: {
input: "$arrayField",
as: "item",
cond: { condition }
}
}
}
}
]);
Sample Data
db.demo334.insertOne({
"Name": "Chris",
"Age": 21,
"details": [
{
"Subject": "MySQL",
"Score": 78
},
{
"Subject": "MongoDB",
"Score": 45
}
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5e52241bf8647eb59e562090")
}
Display the document ?
db.demo334.find().pretty();
{
"_id": ObjectId("5e52241bf8647eb59e562090"),
"Name": "Chris",
"Age": 21,
"details": [
{
"Subject": "MySQL",
"Score": 78
},
{
"Subject": "MongoDB",
"Score": 45
}
]
}
Example: Filter High Scores
Add only subjects with scores >= 70 to the filtered list ?
db.demo334.aggregate([
{
$addFields: {
details: {
$filter: {
input: "$details",
as: "out",
cond: { $gte: ["$$out.Score", 70] }
}
}
}
}
]);
{
"_id": ObjectId("5e52241bf8647eb59e562090"),
"Name": "Chris",
"Age": 21,
"details": [
{
"Subject": "MySQL",
"Score": 78
}
]
}
How It Works
-
$addFieldscreates or replaces thedetailsfield with filtered results -
$filterprocesses each array element and applies the condition -
$$out.Scorereferences the Score field of each array element - Only elements meeting the condition (
$gte: 70) are included in the output
Conclusion
Use $filter within $addFields to create filtered lists based on query conditions. This approach maintains the original document structure while returning only matched array elements.
Advertisements
