On this page本页内容
$in
Returns a boolean indicating whether a specified value is in an array.返回一个布尔值,指示指定值是否在数组中。
$in
has the following operator expression syntax:具有以下运算符表达式语法:
{ $in: [ <expression>, <array expression> ] }
Operand | |
---|---|
<expression> | |
<array expression> |
Unlike the 与$in
query operator, the aggregation $in
operator does not support matching by regular expressions.$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
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
表达式没有给出两个参数,或者第二个参数没有解析为数组。
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 }