$in(聚合)
定义
$in
返回一个布尔值,它可表示指定的值是否在数组中。
{ $in: [ <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 }