“文档” 菜单
文档首页
/
MongoDB Manual
/ / / /

$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 比较顺序。

如果 field 包含一个数组,则 $in 操作符会选择 field 包含数组的文档,该数组至少包含一个与指定数组中的值(如 <value1><value2> 等)相匹配的元素。

$in 操作符会将每个参数与集合中的每个文档进行比较,这可能会导致性能问题。要提高性能:

  • 建议您限制传递给以下运算符的参数数量
    $in 操作符到数十个值。使用数百个或更多参数可能会对查询性能产生负面影响。
  • 在要查询的 field 上创建索引。

注意

本文档介绍 $in 查询操作符。有关 $in 聚合运算符,请参阅 $in(聚合)

对于存储在 MongoDB Atlas 中的数据,您可以在运行 $search 查询时使用 Atlas Search in 运算符。在 $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 操作符。

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 操作符可使用 /pattern/ 形式的正则表达式来指定匹配值。您无法$in 内使用 $regex 操作符表达式。

考虑以下示例:

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

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

提示

另请参阅:

← $gte
$lt →