$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.

CategoryArray
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $filter: { input: <array>, as: <variable>, cond: <condition> } }

⚙️ Parameters

inputThe array expression to filter.
asThe variable name for the current element, referenced as $$variable in cond; optional, defaults to $$this.
condA 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

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'.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏