$in

On this page本页内容

$in

The $in operator selects the documents where the value of a field equals any value in the specified array. $in运算符选择字段值等于指定数组中任何值的文档。To specify an $in expression, use the following prototype:要在表达式中指定$in,请使用以下原型:

For comparison of different BSON type values, see the specified BSON comparison order.有关不同BSON类型值的比较,请参阅指定的BSON比较顺序

{ 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 (for example, <value1>, <value2>, and so on).如果field包含数组,则$in运算符将选择其field包含数组的文档,该数组至少包含一个与指定数组中的值匹配的元素(例如,<value1><value2>,等等)。

Note

This document describes the $in query operator. 本文档介绍了$in查询运算符。For the $in aggregation operator, see $in (aggregation).有关$in聚合运算符,请参阅$in(聚合)

Examples示例

Use the $in Operator to Match Values使用$in运算符匹配值

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. 此查询选择inventory集合中qty字段值为515的所有单据。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.尽管可以使用$or运算符表示此查询,但在对同一字段执行相等性检查时,请选择$in运算符而不是$or运算符。

Use the $in Operator to Match Values in an Array使用$in运算符匹配数组中的值

The collection inventory contains documents that include the field tags, as in the following:集合inventory包含包含字段tags的文档,如下所示:

{ _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".然后,下面的update()操作将sale字段值设置为true,其中tags字段包含至少一个元素与"appliances""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$in运算符与正则表达式一起使用

The $in operator can specify matching values using regular expressions of the form /pattern/. $in运算符可以使用/pattern/形式的正则表达式指定匹配值。You cannot use $regex operator expressions inside an $in.不能在$in中使用$regex运算符表达式。

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 either a string that starts with be or st or an array with at least one element that starts with be or st.此查询选择inventory集合中tags字段包含以best开头的字符串或至少包含一个以best开头的元素的数组的所有文档。

See also参阅

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