$filter (aggregation)

Definition

  • $filter

New in version 3.2.

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

$filter has the following syntax:

  1. { $filter: { input: <array>, as: <string>, cond: <expression> } }

FieldSpecificationinputAn expression thatresolves to an array.asOptional. A name for the variable that represents eachindividual element of the input array. If no name isspecified, the variable name defaults to this.condAn expression that resolvesto a boolean value used to determine if an element should beincluded in the output array. The expression references eachelement of the input array individually with the variablename specified in as.

For more information on expressions, seeExpressions.

Behavior

ExampleResults
  1. { $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:

  1. {
  2. _id: 0,
  3. items: [
  4. { item_id: 43, quantity: 2, price: 10 },
  5. { item_id: 2, quantity: 1, price: 240 }
  6. ]
  7. }
  8. {
  9. _id: 1,
  10. items: [
  11. { item_id: 23, quantity: 3, price: 110 },
  12. { item_id: 103, quantity: 4, price: 5 },
  13. { item_id: 38, quantity: 1, price: 300 }
  14. ]
  15. }
  16. {
  17. _id: 2,
  18. items: [
  19. { item_id: 4, quantity: 1, price: 23 }
  20. ]
  21. }

The following example filters the items array to only includedocuments that have a price greater than or equal to 100:

  1. db.sales.aggregate([
  2. {
  3. $project: {
  4. items: {
  5. $filter: {
  6. input: "$items",
  7. as: "item",
  8. cond: { $gte: [ "$$item.price", 100 ] }
  9. }
  10. }
  11. }
  12. }
  13. ])

The operation produces the following results:

  1. {
  2. "_id" : 0,
  3. "items" : [
  4. { "item_id" : 2, "quantity" : 1, "price" : 240 }
  5. ]
  6. }
  7. {
  8. "_id" : 1,
  9. "items" : [
  10. { "item_id" : 23, "quantity" : 3, "price" : 110 },
  11. { "item_id" : 38, "quantity" : 1, "price" : 300 }
  12. ]
  13. }
  14. { "_id" : 2, "items" : [ ] }