How to Use $filter in Aggregation in MongoDB
In MongoDB aggregation, use the
$filter operator to select elements from an array that meet a specified condition. It takes an input array, a condition expression, and returns a filtered array with only matching elements.Syntax
The $filter operator has three main parts:
- input: The array to filter.
- as: A variable name for each element in the array.
- cond: A condition expression that returns true for elements to keep.
json
{
$filter: {
input: <array>,
as: <variable_name>,
cond: <condition_expression>
}
}Example
This example filters an array of scores to keep only those greater than 70.
mongodb
db.students.aggregate([
{
$project: {
name: 1,
highScores: {
$filter: {
input: "$scores",
as: "score",
cond: { $gt: ["$$score", 70] }
}
}
}
}
])Output
[
{ "_id": ObjectId("..."), "name": "Alice", "highScores": [85, 90] },
{ "_id": ObjectId("..."), "name": "Bob", "highScores": [75] }
]
Common Pitfalls
Common mistakes when using $filter include:
- Not using
$$before the variable name insidecond. For example, use$$scorenot$score. - Passing a non-array value to
input, which causes errors. - Using incorrect condition syntax that does not return a boolean.
json
/* Wrong: missing $$ before variable */ { $filter: { input: "$scores", as: "score", cond: { $gt: ["$score", 70] } // Incorrect } } /* Correct: use $$score */ { $filter: { input: "$scores", as: "score", cond: { $gt: ["$$score", 70] } // Correct } }
Quick Reference
| Part | Description | Example |
|---|---|---|
| input | Array to filter | "$scores" |
| as | Variable name for each element | "score" |
| cond | Condition to keep element | { $gt: ["$$score", 70] } |
Key Takeaways
Use $filter in aggregation to select array elements matching a condition.
Always prefix the variable in cond with $$ to reference array elements.
Input must be an array; otherwise, $filter will error.
The cond expression must return true or false for each element.
Use $filter inside $project or other pipeline stages to reshape documents.