$in (aggregation)

Definition

  • $in

New in version 3.4.

Returns a boolean indicating whether a specified value is in anarray.

$in has the following operator expression syntax:

  1. { $in: [ <expression>, <array expression> ] }

OperandDescription<expression>Any valid expression expression.<array expression>Any valid expression thatresolves to an array.

Unlike the $in query operator, the aggregation$in operator does not support matching byregular expressions.

ExampleResults{ $in: [ 2, [ 1, 2, 3 ] ] }true{ $in: [ "abc", [ "xyz", "abc" ] ] }true{ $in: [ "xy", [ "xyz", "abc" ] ] }false{ $in: [ [ "a" ], [ "a" ] ] }false{ $in: [ [ "a" ], [ [ "a" ] ] ] }true{ $in: [ /^a/, [ "a" ] ] }false{ $in: [ /^a/, [ /^a/ ] ] }true

Behavior

$in fails with an error in either of thefollowing cases: if the $in expression is not given exactly twoarguments, or if the second argument does not resolve to an array.

Example

A collection named fruit has the following documents:

  1. { "_id" : 1, "location" : "24th Street",
  2. "in_stock" : [ "apples", "oranges", "bananas" ] }
  3. { "_id" : 2, "location" : "36th Street",
  4. "in_stock" : [ "bananas", "pears", "grapes" ] }
  5. { "_id" : 3, "location" : "82nd Street",
  6. "in_stock" : [ "cantaloupes", "watermelons", "apples" ] }

The following aggregation operation looks at the in_stock array ineach document and determines whether the string bananas is present.

  1. db.fruit.aggregate([
  2. {
  3. $project: {
  4. "store location" : "$location",
  5. "has bananas" : {
  6. $in: [ "bananas", "$in_stock" ]
  7. }
  8. }
  9. }
  10. ])

The operation returns the following results:

  1. { "_id" : 1, "store location" : "24th Street", "has bananas" : true }
  2. { "_id" : 2, "store location" : "36th Street", "has bananas" : true }
  3. { "_id" : 3, "store location" : "82nd Street", "has bananas" : false }