$setDifference(聚合)
定义
$setDifference
获取两个集合并返回一个数组,其中包含仅存在于第一个集合中的元素; ie 执行 相对补集 第二组相对于第一组的大小。
$setDifference
通过以下语法实现:{ $setDifference: [ <expression1>, <expression2> ] }
行为
$setDifference
对数组执行集合操作,将数组视为集合。如果数组包含重复条目,$setDifference
会忽略重复条目。$setDifference
会忽略元素的顺序。
$setDifference
过滤掉结果中的重复项,以输出仅包含唯一条目的数组。 输出数组中元素的顺序未指定。
如果集合包含嵌套数组元素,$setDifference
不会下降进入嵌套数组,而是在顶层计算数组。
例子 | 结果 | ||
---|---|---|---|
|
| ||
|
|
例子
考虑包含以下文档的 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" ] } ] )
以下操作使用$setDifference
操作符返回在flowerFieldB
数组中找到但在flowerFieldA
数组中未找到的元素的数组:
db.flowers.aggregate( [ { $project: { flowerFieldA: 1, flowerFieldB: 1, inBOnly: { $setDifference: [ "$flowerFieldB", "$flowerFieldA" ] }, _id: 0 } } ] )
操作返回以下结果:
{ "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ "rose", "orchid" ], "inBOnly" : [ ] } { "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ "orchid", "rose", "orchid" ], "inBOnly" : [ ] } { "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ "rose", "orchid", "jasmine" ], "inBOnly" : [ "jasmine" ] } { "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ "jasmine", "rose" ], "inBOnly" : [ "jasmine" ] } { "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ ], "inBOnly" : [ ] } { "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ [ "rose" ], [ "orchid" ] ], "inBOnly" : [ [ "rose" ], [ "orchid" ] ] } { "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ [ "rose", "orchid" ] ], "inBOnly" : [ [ "rose", "orchid" ] ] } { "flowerFieldA" : [ ], "flowerFieldB" : [ ], "inBOnly" : [ ] } { "flowerFieldA" : [ ], "flowerFieldB" : [ "rose" ], "inBOnly" : [ "rose" ] }