$in
$in
- The
$in
operator selects the documents where the valueof a field equals any value in the specified array. To specify an$in
expression, use the following prototype:
For comparison of different BSON type values, see the specifiedBSON comparison order.
- { field: { $in: [<value1>, <value2>, ... <valueN> ] } }
If the field
holds an array, then the $in
operatorselects the documents whose field
holds an array that containsat least one element that matches a value in the specified array(e.g. <value1>
, <value2>
, etc.)
Changed in version 2.6: MongoDB 2.6 removes the combinatorial limit for the $in
operator that exists for earlier versions of the operator.
Examples
Use the $in Operator to Match Values
Consider the following example:
- db.inventory.find( { qty: { $in: [ 5, 15 ] } } )
This query selects all documents in the inventory
collection where the qty
field value is either 5
or15
. Although you can express this query using the$or
operator, choose the $in
operator ratherthan the $or
operator when performing equality checks onthe same field.
Use the $in Operator to Match Values in an Array
The collection inventory
contains documents that include the fieldtags
, as in the following:
- { _id: 1, item: "abc", qty: 10, tags: [ "school", "clothing" ], sale: false }
Then, the following update()
operation willset the sale
field value to true
where the tags
field holdsan array with at least one element matching either "appliances"
or"school"
.
- db.inventory.update(
- { tags: { $in: ["appliances", "school"] } },
- { $set: { sale:true } }
- )
For additional examples in querying arrays, see:
For additional examples in querying, see:
Use the $in Operator with a Regular Expression
The $in
operator can specify matching values using regularexpressions of the form /pattern/
. You cannot use $regex
operator expressions inside an $in
.
Consider the following example:
- db.inventory.find( { tags: { $in: [ /^be/, /^st/ ] } } )
This query selects all documents in the inventory
collection wherethe tags
field holds either a string that starts with be
orst
or an array with at least one element that starts with be
orst
.
See also
find()
, update()
, $or
, $set
, $elemMatch
.