$in (aggregation)

On this page本页内容

Definition定义

$in

New in version 3.4.版本3.4中的新功能。

Returns a boolean indicating whether a specified value is in an array.返回一个布尔值,指示指定的值是否在数组中。

Note

This document describes the $in aggregation operator. 本文档介绍了$in聚合运算符。For the $in query operator, see $in.有关$in查询运算符,请参阅$in

$in has the following operator expression syntax:$in具有以下运算符表达式语法

{ $in: [ <expression>, <array expression> ] }
Operand运算数Description描述
<expression> Any valid expression expression.任何有效的 表达式
<array expression> Any valid expression that resolves to an array.解析为数组的任何有效 表达式

Unlike the $in query operator, the aggregation $in operator does not support matching by regular expressions.$in查询运算符不同,聚合$in运算符不支持通过正则表达式进行匹配。

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 fails with an error in either of the following cases: if the $in expression is not given exactly two arguments, or if the second argument does not resolve to an array.$in在以下任何一种情况下都会失败,并出现错误:如果$in表达式没有恰好给出两个参数,或者如果第二个参数没有解析为数组。

Example示例

A collection named fruit has the following documents:名为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" ] }

The following aggregation operation looks at the in_stock array in each document and determines whether the string bananas is present.下面的聚合操作将查看每个文档中的in_stock数组,并确定字符串bananas是否存在。

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

The operation returns the following results:操作返回以下结果:

{ "_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 }