$in$in操作符选择字段值等于指定数组中任何值的文档。
兼容性
可以使用 $in 查找托管在以下环境中的部署:
MongoDB Atlas:用于云中 MongoDB 部署的完全托管服务
MongoDB Enterprise:基于订阅、自我管理的 MongoDB 版本
MongoDB Community:源代码可用、免费使用且可自行管理的 MongoDB 版本
语法
要指定 $in 表达式,请使用以下原型:
{ field: { $in: [<value1>, <value2>, ... <valueN> ] } }
关于不同 BSON 类型值的比较,请参阅指定的 BSON 比较顺序。
如果 field 包含一个数组,则 $in 操作符会选择 field 包含数组的文档,该数组至少包含一个与指定数组中的值(如 <value1>、<value2> 等)相匹配的元素。
$in 操作符会将每个参数与集合中的每个文档进行比较,这可能会导致性能问题。要提高性能:
- 建议您限制传递给以下运算符的参数数量
$in操作符到数十个值。使用数百个或更多参数可能会对查询性能产生负面影响。
在要查询的
field上创建索引。
使用 Atlas Search 查询 Atlas 数据
对于存储在 MongoDB Atlas 中的数据,您可以在运行 $search 查询时使用 Atlas Search in Operator 操作符。在 $search 之后运行 $in 的性能低于使用 in Operator 操作符运行 $search 的性能。
要学习;了解有关此操作符的Atlas Search版本的更多信息,请参阅Atlas文档中的in Operator操作符。
示例
创建 inventory 集合:
db.inventory.insertMany( [ { "item": "Pens", "quantity": 350, "tags": [ "school", "office" ] }, { "item": "Erasers", "quantity": 15, "tags": [ "school", "home" ] }, { "item": "Maps", "tags": [ "office", "storage" ] }, { "item": "Books", "quantity": 5, "tags": [ "school", "storage", "home" ] } ] )
使用 $in 操作符匹配值
考虑以下示例:
db.inventory.find( { quantity: { $in: [ 5, 15 ] } }, { _id: 0 } )
此查询选择 inventory 集合中 quantity 字段的值为 5 或 15 的所有文档。
{ item: 'Erasers', quantity: 15, tags: [ 'school', 'home' ] }, { item: 'Books', quantity: 5, tags: [ 'school', 'storage', 'home' ] }
虽然可以使用 $or 操作符编写此查询,但在对同一字段执行相等性检查时,应使用 $in 操作符,而不是 $or 操作符。
使用 $in 操作符匹配数组中的值
当 tags 数组至少有一个与 "home" 或 "school" 匹配的元素时,以下 updateMany() 操作将 exclude 字段设置为 false。
db.inventory.updateMany( { tags: { $in: [ "home", "school" ] } }, { $set: { exclude: false } } )
示例输出:
{ item: 'Pens', quantity: 350, tags: [ 'school', 'office' ], exclude: false }, { item: 'Erasers', quantity: 15, tags: [ 'school', 'home' ], exclude: false }, { item: 'Books', quantity: 5, tags: [ 'school', 'storage', 'home' ], exclude: false }
有关查询数组的其他示例,请参阅:
有关查询的其他示例,请参阅查询文档。
将 $in 操作符与正则表达式结合使用
$in 操作符可使用 /pattern/ 形式的正则表达式来指定匹配值。您无法在 $in 内使用 $regex 操作符表达式。
考虑以下示例:
db.inventory.find( { tags: { $in: [ /^be/, /^st/ ] } } )
此查询选择inventory集合中的所有文档,其中tags字段包含以be或st开头的字符串,或者包含至少一个以be或st开头的元素的数组。