$in (aggregation)

在本页面

Definition

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

$in具有以下运算符表达式语法

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

$in查询运算符不同,聚合$in运算符不支持regular expressions匹配。

Example Results
{ $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

Behavior

$in在以下两种情况下都会失败,并显示错误:$ in 表达式未恰好给出两个参数,或者第二个参数未解析为数组。

Example

名为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 }
首页