$setIntersection(聚合)
MongoDB5.0 已于 10 月2024 结束生命周期。不再支持此版本的文档。要升级5.0 部署,请参阅 MongoDB6 。0 升级程序。
定义
$setIntersection
接收两个或多个数组,并返回一个数组,其中包含出现在每个输入数组中的元素。
$setIntersection
通过以下语法实现:{ $setIntersection: [ <array1>, <array2>, ... ] }
行为
$setIntersection
对数组执行集合操作,将数组视为集合。如果数组包含重复条目,$setIntersection
会忽略重复条目。$setIntersection
会忽略元素的顺序。
$setIntersection
过滤掉结果中的重复项,以输出仅包含唯一条目的数组。 输出数组中元素的顺序未指定。
如果未找到交集(即输入数组不包含公共元素), $setIntersection
将返回一个空数组。
如果集合包含嵌套数组元素,$setIntersection
不会下降进入嵌套数组,而是在顶层计算数组。
例子 | 结果 | ||
---|---|---|---|
|
| ||
|
|
例子
本部分包含展示如何将 $setIntersection
与集合一起使用的示例。
元素数组示例
考虑包含以下文档的 flowers
集合:
db.flowers.insertMany( [ { "_id" : 1, "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ "rose", "orchid" ] }, { "_id" : 2, "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ "orchid", "rose", "orchid" ] }, { "_id" : 3, "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ "rose", "orchid", "jasmine" ] }, { "_id" : 4, "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ "jasmine", "rose" ] }, { "_id" : 5, "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ ] }, { "_id" : 6, "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ [ "rose" ], [ "orchid" ] ] }, { "_id" : 7, "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ [ "rose", "orchid" ] ] }, { "_id" : 8, "flowerFieldA" : [ ], "flowerFieldB" : [ ] }, { "_id" : 9, "flowerFieldA" : [ ], "flowerFieldB" : [ "rose" ] } ] )
以下操作使用$setIntersection
操作符返回flowerFieldA
数组和flowerFieldB
数组共有的元素数组:
db.flowers.aggregate( [ { $project: { flowerFieldA: 1, flowerFieldB: 1, commonToBoth: { $setIntersection: [ "$flowerFieldA", "$flowerFieldB" ] }, _id: 0 } } ] )
操作返回以下结果:
{ "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ "rose", "orchid" ], "commonToBoth" : [ "orchid", "rose" ] } { "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ "orchid", "rose", "orchid" ], "commonToBoth" : [ "orchid", "rose" ] } { "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ "rose", "orchid", "jasmine" ], "commonToBoth" : [ "orchid", "rose" ] } { "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ "jasmine", "rose" ], "commonToBoth" : [ "rose" ] } { "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ ], "commonToBoth" : [ ] } { "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ [ "rose" ], [ "orchid" ] ], "commonToBoth" : [ ] } { "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ [ "rose", "orchid" ] ], "commonToBoth" : [ ] } { "flowerFieldA" : [ ], "flowerFieldB" : [ ], "commonToBoth" : [ ] } { "flowerFieldA" : [ ], "flowerFieldB" : [ "rose" ], "commonToBoth" : [ ] }