$setDifference (aggregation)
Definition
New in version 2.6.
Takes two sets and returns an array containing the elements thatonly exist in the first set; i.e. performs a relative complement) of thesecond set relative to the first.
$setDifference
has the following syntax:
- { $setDifference: [ <expression1>, <expression2> ] }
The arguments can be any valid expression as long as they each resolve to an array.For more information on expressions, seeExpressions.
Behavior
$setDifference
performs set operation on arrays, treating arraysas sets. If an array contains duplicate entries, $setDifference
ignores the duplicate entries. $setDifference
ignores the order ofthe elements.
$setDifference
filters out duplicates in its result to output anarray that contain only unique entries. The order of the elements inthe output array is unspecified.
If a set contains a nested array element, $setDifference
does not descendinto the nested array but evaluates the array at top-level.
Example | Result |
---|---|
|
|
|
|
Example
Consider an experiments
collection with the following documents:
- { "_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" ] }
The following operation uses the $setDifference
operatorto return an array of elements found in the B
array but _not_in the A
array:
- db.experiments.aggregate(
- [
- { $project: { A: 1, B: 1, inBOnly: { $setDifference: [ "$B", "$A" ] }, _id: 0 } }
- ]
- )
The operation returns the following results:
- { "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" ] }