$setIntersection (aggregation)

在本页面

Definition

获取两个或更多数组,并返回一个包含每个 Importing 数组中出现的元素的数组。

$setIntersection具有以下语法:

{ $setIntersection: [ <array1>, <array2>, ... ] }

参数可以是任何有效的expression,只要它们每个都解析为数组即可。有关表达式的更多信息,请参见Expressions

Behavior

$setIntersection对数组执行 set 操作,将数组视为 set。如果数组包含重复项,则$setIntersection会忽略重复项。 $setIntersection忽略元素的 Sequences。

$setIntersection过滤掉结果中的重复项,以输出仅包含唯一条目的数组。输出数组中元素的 Sequences 未指定。

如果集合包含嵌套数组元素,则$setIntersection不会*降级到嵌套数组中,而是在顶级对数组进行求值。

Example Result
{ $setIntersection: [ [ "a", "b", "a" ], [ "b", "a" ] ] } [ "b", "a" ]
{ $setIntersection: [ [ "a", "b" ], [ [ "a", "b" ] ] ] } [ ]

Example

考虑包含以下文档的experiments集合:

{ "_id" : 1, "A" : [ "red", "blue" ], "B" : [ "red", "blue" ] }
{ "_id" : 2, "A" : [ "red", "blue" ], "B" : [ "blue", "red", "blue" ] }
{ "_id" : 3, "A" : [ "red", "blue" ], "B" : [ "red", "blue", "green" ] }
{ "_id" : 4, "A" : [ "red", "blue" ], "B" : [ "green", "red" ] }
{ "_id" : 5, "A" : [ "red", "blue" ], "B" : [ ] }
{ "_id" : 6, "A" : [ "red", "blue" ], "B" : [ [ "red" ], [ "blue" ] ] }
{ "_id" : 7, "A" : [ "red", "blue" ], "B" : [ [ "red", "blue" ] ] }
{ "_id" : 8, "A" : [ ], "B" : [ ] }
{ "_id" : 9, "A" : [ ], "B" : [ "red" ] }

以下操作使用$setIntersection运算符返回A数组和B数组共同的元素数组:

db.experiments.aggregate(
   [
     { $project: { A: 1, B: 1, commonToBoth: { $setIntersection: [ "$A", "$B" ] }, _id: 0 } }
   ]
)

该操作返回以下结果:

{ "A" : [ "red", "blue" ], "B" : [ "red", "blue" ], "commonToBoth" : [ "blue", "red" ] }
{ "A" : [ "red", "blue" ], "B" : [ "blue", "red", "blue" ], "commonToBoth" : [ "blue", "red" ] }
{ "A" : [ "red", "blue" ], "B" : [ "red", "blue", "green" ], "commonToBoth" : [ "blue", "red" ] }
{ "A" : [ "red", "blue" ], "B" : [ "green", "red" ], "commonToBoth" : [ "red" ] }
{ "A" : [ "red", "blue" ], "B" : [ ], "commonToBoth" : [ ] }
{ "A" : [ "red", "blue" ], "B" : [ [ "red" ], [ "blue" ] ], "commonToBoth" : [ ] }
{ "A" : [ "red", "blue" ], "B" : [ [ "red", "blue" ] ], "commonToBoth" : [ ] }
{ "A" : [ ], "B" : [ ], "commonToBoth" : [ ] }
{ "A" : [ ], "B" : [ "red" ], "commonToBoth" : [ ] }
首页