$in
$in关于
$in运算符选择字段值等于指定数组中任何值的文档。
兼容性
您可以使用$in在以下环境中部署
MongoDB Atlas:云中MongoDB部署的全托管服务
MongoDB Enterprise:基于订阅、自管理的MongoDB版本
MongoDB Community:源代码可用的、免费使用且自管理的MongoDB版本
语法
要指定一个 $in 表达式,使用以下原型
{ field: { $in: [<value1>, <value2>, ... <valueN> ] } }
有关不同 BSON 类型值的比较,请参阅指定的 BSON 比较顺序。
如果 字段 包含一个数组,那么 $in 操作符会选择那些 字段 包含一个数组且至少包含一个与指定数组中的值匹配的元素的文档(例如,<value1>,<value2> 等)。
$in 操作符将每个参数与集合中的每个文档进行比较,这可能会导致性能问题。为了提高性能
- 建议您限制传递给
$in操作符的参数数量为十几个。使用数百个或更多的参数可能会对查询性能产生负面影响。
在您想要查询的
字段上创建索引。
通过 Atlas Search 在 Atlas 上查询数据
对于存储在MongoDB Atlas中的数据,您可以在执行Atlas Search in运算符时使用$search查询。在执行$search后运行$in的效率低于使用in运算符执行$search。
有关此运算符的Atlas Search版本的信息,请参阅Atlas文档中的in运算符。
示例
创建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' ] }
使用 $in 操作符匹配数组中的值
以下 updateMany() 操作在 tags 数组至少有一个元素匹配 "home" 或 "school" 时将 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 开头的数组的文档。