$filter (aggregation)
On this page
Definition
Compatibility
You can use $filter
for deployments hosted in the following
environments:
MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud
MongoDB Enterprise: The subscription-based, self-managed version of MongoDB
MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB
Syntax
$filter
has the following syntax:
{ $filter: { input: <array>, cond: <expression>, as: <string>, limit: <number expression> } }
Field | Specification |
---|---|
| An expression that resolves to an array. If If |
| An expression that resolves
to a boolean value used to determine if an element should be
included in the output array. The expression references each
element of the |
| Optional. A name for the variable that represents each
individual element of the |
| Optional. A number expression that restricts the number of matching
array elements that If the specified |
For more information on expressions, see Expressions.
Behavior
Example | Results | ||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
|
|
Example
A collection sales
has the following documents:
{ _id: 0, items: [ { item_id: 43, quantity: 2, price: 10 }, { item_id: 2, quantity: 1, price: 240 } ] } { _id: 1, items: [ { item_id: 23, quantity: 3, price: 110 }, { item_id: 103, quantity: 4, price: 5 }, { item_id: 38, quantity: 1, price: 300 } ] } { _id: 2, items: [ { item_id: 4, quantity: 1, price: 23 } ] }
The following example filters the items
array to only include
documents that have a price
greater than or equal to 100
:
db.sales.aggregate([ { $project: { items: { $filter: { input: "$items", as: "item", cond: { $gte: [ "$$item.price", 100 ] } } } } } ])
The operation produces the following results:
{ "_id" : 0, "items" : [ { "item_id" : 2, "quantity" : 1, "price" : 240 } ] } { "_id" : 1, "items" : [ { "item_id" : 23, "quantity" : 3, "price" : 110 }, { "item_id" : 38, "quantity" : 1, "price" : 300 } ] } { "_id" : 2, "items" : [ ] }