$filter (Filter Array)
Last updated: 2026-10-09
$filter (Filter Array)
$filter walks an array, keeps the elements that satisfy a condition, and returns a new array. It is the go-to operator for filtering arrays inside aggregation expressions. Typical use cases: picking shipped items from an order, dropping invalid tags, or selecting reviews above a score threshold. Its syntax requires an input array, an as variable name, and a cond expression that references the current element via $$variable. It only removes elements without transforming them; pair it with $map when elements must also change. A null input yields null.
| Category | Array |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $filter: { input: <array>, as: <variable>, cond: <condition> } }
⚙️ Parameters
| input | The array expression to filter. |
|---|---|
| as | The variable name for the current element, referenced as $$variable in cond; optional, defaults to $$this. |
| cond | A condition expression resolving to a boolean; decides which elements remain. |
Returns:A new array of elements satisfying the condition; null if input is null
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $filter: keep only items with stock above zero
db.orders.aggregate([
{ $project: {
inStock: { $filter: { input: '$items', as: 'it', cond: { $gt: ['$$it.qty', 0] } } }
} }
])
Output:
{ '_id': 1, 'inStock': [ { 'sku': 'A01', 'qty': 2 } ] }
{ '_id': 2, 'inStock': [] }
📌 Notes
- Reference the current element in cond with a $$ prefix, e.g. $$it or $$this
- $filter only removes elements; nest a $map to also transform them
- Elements whose condition is null or false are dropped; a null input yields null
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QWhat is the difference between $filter and $map?
A$filter removes elements by condition without changing them; $map transforms each element without changing the count. They are often combined.
QHow do I reference the variable in cond?
APrefix the variable with two dollar signs, e.g. { $gt: ['$$it.qty', 0] }; use $$this when as is omitted.
QCan $filter work on an array of objects?
AYes — access object fields with $$variable.field in cond, e.g. '$$it.price'.