Definition
$inReturns a boolean indicating whether a specified value is in an array.
Note
This document describes the
$inaggregation operator. For the$inquery operator, see $in (query predicate operator).$inhas the following operator expression syntax:{ $in: [ <expression>, <array expression> ] } OperandDescription<expression>Any valid expression expression.
<array expression>Any valid expression that resolves to an array.
Unlike the
$inquery operator, the aggregation$inoperator does not support matching by regular 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 the following cases: if the $in expression is not given exactly two arguments, or if the second argument does not resolve to an array.
Example
The following example uses the movies collection from the sample_mflix
sample dataset. For details on how to load this dataset into your deployment, see Load the sample dataset.
This aggregation operation looks at the genres array in each movie and determines whether the string "Drama" is present:
db.movies.aggregate( [ { $match: { runtime: { $gt: 1000 } } }, { $project: { _id: 0, title: 1, hasDrama: { $in: [ "Drama", "$genres" ] } } } ] )
[ { title: 'Centennial', hasDrama: true }, { title: 'Baseball', hasDrama: false } ]