Docs 菜单

Docs 主页开发应用程序MongoDB Manual

$in(聚合)

在此页面上

  • 定义
  • 行为
  • 例子
$in

返回一个布尔值,它可表示指定的值是否在数组中。

注意

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

$in采用以下操作符表达式语法:

{ $in: [ <expression>, <array expression> ] }
操作数
说明
<expression>
任何有效的表达式
<array expression>
任何解析为数组的有效表达式

$in查询运算符不同,聚合$in运算符不支持通过正则表达式进行匹配。

例子
结果
{ $in: [ 2, [ 1, 2, 3 ] ] }
true
{ $in: [ "abc", [ "xyz", "abc" ] ] }
true
{ $in: [ "xy", [ "xyz", "abc" ] ] }
false
{ $in: [ [ "a" ], [ "a" ] ] }
false
{ $in: [ [ "a" ], [ [ "a" ] ] ] }
true
{ $in: [ /^a/, [ "a" ] ] }
false
{ $in: [ /^a/, [ /^a/ ] ] }
true

$in 在以下任一情况均会失败并出现错误:如果未向 $in 表达式提供实际两个参数,或是第二个参数未解析为数组。

名为 fruit 的集合包含以下文档:

{ "_id" : 1, "location" : "24th Street",
"in_stock" : [ "apples", "oranges", "bananas" ] }
{ "_id" : 2, "location" : "36th Street",
"in_stock" : [ "bananas", "pears", "grapes" ] }
{ "_id" : 3, "location" : "82nd Street",
"in_stock" : [ "cantaloupes", "watermelons", "apples" ] }

以下聚合操作查看每个文档中的 in_stock 数组,并确定是否存在字符串 bananas

db.fruit.aggregate([
{
$project: {
"store location" : "$location",
"has bananas" : {
$in: [ "bananas", "$in_stock" ]
}
}
}
])

操作返回以下结果:

{ "_id" : 1, "store location" : "24th Street", "has bananas" : true }
{ "_id" : 2, "store location" : "36th Street", "has bananas" : true }
{ "_id" : 3, "store location" : "82nd Street", "has bananas" : false }
← $ifNull(聚合)

在此页面上