- Reference >
- Operators >
- Aggregation Pipeline Operators >
- Set Operators (Aggregation) >
- $setDifference (aggregation)
$setDifference (aggregation)¶
- $setDifference¶
2.6 新版功能.
Takes two sets and returns an array containing the elements that only exist in the first set; i.e. performs a relative complement of the second 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, see Expressions.
Behavior¶
$setDifference performs set operation on arrays, treating arrays as sets. If an array contains duplicate entries, $setDifference ignores the duplicate entries. $setDifference ignores the order of the elements.
$setDifference filters out duplicates in its result to output an array that contain only unique entries. The order of the elements in the output array is unspecified.
If a set contains a nested array element, $setDifference does not descend into the nested array but evaluates the array at top-level.
Example | Result | |
---|---|---|
{ $setDifference: [ [ "a", "b", "a" ], [ "b", "a" ] ] } | [ ] | |
{ $setDifference: [ [ "a", "b" ], [ [ "a", "b" ] ] ] } | [ "a", "b" ] |
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 operator to 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" ] }