Docs 菜单

Docs 主页开发应用程序MongoDB Manual

$in

在此页面上

  • 兼容性
  • 语法
  • 使用 Atlas Search 查询 Atlas 数据
  • 举例
  • 使用 $in 操作符匹配值
  • 使用 $in 操作符匹配数组中的值
  • $in 操作符与正则表达式结合使用
$in

$in操作符选择字段值等于指定数组中任意值的文档。

可以使用 $in 查找托管在以下环境中的部署:

  • MongoDB Atlas :用于在云中部署 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 →