Navigation
This version of the documentation is archived and no longer supported.

$in

$in

The $in operator selects the documents where the value of a field equals any value in the specified array. To specify an $in expression, use the following prototype:

{ field: { $in: [<value1>, <value2>, ... <valueN> ] } }

If the field holds an array, then the $in operator selects the documents whose field holds an array that contains at least one element that matches a value in the specified array (e.g. <value1>, <value2>, etc.)

Note

Querying with two or more $in expressions (e.g. { a: { $in: [ "a", "b", "c" ] }, b: { $in: [ "b", "c" ] } } ) can hit a combinatorial limit if the query uses a compound index on these fields (e.g. { a: 1, b: 1 } ). Specifically, if the number of combinations (i.e. the product of the number of distinct elements in the respective arrays) is equal to or greater than 4000000, MongoDB will throw an exception of "combinatorial limit of $in partitioning of result set exceeded".

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 or 15. Although you can express this query using the $or operator, choose the $in operator rather than the $or operator when performing equality checks on the same field.

Use the $in Operator to Match Values in an Array

The collection inventory contains documents that include the field tags, as in the following:

{ _id: 1, item: "abc", qty: 10, tags: [ "school", "clothing" ], sale: false }

Then, the following update() operation will set the sale field value to true where the tags field holds an array with at least one element matching either "appliances" or "school".

db.inventory.update(
                     { tags: { $in: ["appliances", "school"] } },
                     { $set: { sale:true } }
                   )

Use the $in Operator with a Regular Expression

The $in operator can specify matching values using regular expressions 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 where the tags field holds an array that contains at least one element that starts with either be or st.

See also

find(), update(), $or, $set.

←   $gte $lt  →