文档菜单
文档首页
/
MongoDB 手册
/ / / /

$in

本页内容

  • 兼容性
  • 语法
  • 使用Atlas Search在Atlas上查询数据
  • 示例
  • 使用$in运算符来匹配值
  • 使用$in运算符匹配数组中的值
  • 使用正则表达式与$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 操作符的参数数量为十几个。使用数百个或更多的参数可能会对查询性能产生负面影响。
  • 在您想要查询的 字段 上创建索引。

注意

本文档描述了 $in 查询操作符。有关 $in 聚合操作符,请参阅 $in (聚合)。

对于存储在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" ] }
] )

考虑以下示例

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 操作符。

以下 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 操作符可以使用形式为 /pattern/ 的正则表达式指定匹配值。您 不能$in. 内部使用 $regex 操作符表达式。

考虑以下示例

db.inventory.find( { tags: { $in: [ /^be/, /^st/ ] } } )

此查询选择所有在 inventory 集合中,tags 字段包含以 best 开头的字符串或至少包含一个以 best 开头的数组的文档。

提示

另请参阅

返回

$gte