Docs 菜单
Docs 主页
/ /

$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 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" ] }
] )

此查询选择 inventory集合中 quantity字段的值为 515 的文档:

db.inventory.find( { quantity: { $in: [ 5, 15 ] } }, { _id: 0 } )

输出:

{ item: 'Erasers', quantity: 15, tags: [ 'school', 'home' ] },
{ item: 'Books', quantity: 5, tags: [ 'school', 'storage', 'home' ] }

虽然可以使用$or 操作符写入查询,但在对同一字段执行相等性检查时,请使用$in 操作符而不是$or 操作符。

updateMany()excludefalse tags大量至少有一个与"home" 或 匹配的元素时,以下 操作会将"school" 字段设置为 :

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/ 形式的正则表达式选择文档。不能在 中使用$regex $in表达式。

此查询选择 inventory集合中 tags字段以 best 开头的文档:

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

该查询选择 inventory集合中的所有文档,其中 tags字段要么是以 best 开头的字符串,要么是一个大量,其中至少有一个以 best 开头的元素。

后退

$gte

在此页面上