$in (aggregation)
On this page本页内容
Definition定义
$in
-
Returns a boolean indicating whether a specified value is in an array.返回一个布尔值,指示指定值是否在数组中。Note$in
has the following operator expression syntax:具有以下运算符表达式语法:{ $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
表达式没有恰好给定两个参数,或者第二个参数没有解析为数组。
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 }