$setDifference (aggregation)

在本页面

Definition

  • $setDifference
    • 2.6 版的新功能。

接受两个集合并返回一个数组,其中包含仅存在于第一集合中的元素;即执行相对于第一组的relative complement

$setDifference具有以下语法:

{ $setDifference: [ <expression1>, <expression2> ] }

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

Behavior

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

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

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

ExampleResult
{ $setDifference: [ [ "a", "b", "a" ], [ "b", "a" ] ] }[ ]
{ $setDifference: [ [ "a", "b" ], [ [ "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" ] }

以下操作使用$setDifference运算符返回在B数组中找到但在A数组中不是的元素数组:

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

该操作返回以下结果:

{ "A" : [ "red", "blue" ], "B" : [ "red", "blue" ], "inBOnly" : [ ] }
{ "A" : [ "red", "blue" ], "B" : [ "blue", "red", "blue" ], "inBOnly" : [ ] }
{ "A" : [ "red", "blue" ], "B" : [ "red", "blue", "green" ], "inBOnly" : [ "green" ] }
{ "A" : [ "red", "blue" ], "B" : [ "green", "red" ], "inBOnly" : [ "green" ] }
{ "A" : [ "red", "blue" ], "B" : [ ], "inBOnly" : [ ] }
{ "A" : [ "red", "blue" ], "B" : [ [ "red" ], [ "blue" ] ], "inBOnly" : [ [ "red" ], [ "blue" ] ] }
{ "A" : [ "red", "blue" ], "B" : [ [ "red", "blue" ] ], "inBOnly" : [ [ "red", "blue" ] ] }
{ "A" : [ ], "B" : [ ], "inBOnly" : [ ] }
{ "A" : [ ], "B" : [ "red" ], "inBOnly" : [ "red" ] }