OPTIONS

$filter (aggregation)

On this page

Definition

$filter

New in version 3.2.

Selects a subset of the array to return based on the specified condition. Returns an array with only those elements that match the condition. The returned elements are in the original order.

$filter has the following syntax:

{ $filter: { input: <array>, as: <string>, cond: <expression> } }
Field Specification
input An expression that resolves to an array.
as The variable name for the element in the input array. The as expression accesses each element in the input array by this variable.
cond The expression that determines whether to include the element in the resulting array. The expression accesses the element by the variable name specified in as.

For more information on expressions, see Expressions.

Behavior

Example Results
{
  $filter: {
     input: [ 1, "a", 2, null, 3.1, NumberLong(4), "5" ],
     as: "num",
     cond: { $and: [
        { $gte: [ "$$num", NumberLong("-9223372036854775807") ] },
        { $lte: [ "$$num", NumberLong("9223372036854775807") ] }
      ] }
  }
}
[ 1, 2, 3.1, NumberLong(4) ]

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" : [ ] }