$setDifference (aggregation)

Definition

  • $setDifference

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:

  1. { $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, $setDifferenceignores 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.

ExampleResult
  1. { $setDifference: [ [ "a", "b", "a" ], [ "b", "a" ] ] }
  1. [ ]
  1. { $setDifference: [ [ "a", "b" ], [ [ "a", "b" ] ] ] }
  1. [ "a", "b" ]

Example

Consider an experiments collection with the following documents:

  1. { "_id" : 1, "A" : [ "red", "blue" ], "B" : [ "red", "blue" ] }
  2. { "_id" : 2, "A" : [ "red", "blue" ], "B" : [ "blue", "red", "blue" ] }
  3. { "_id" : 3, "A" : [ "red", "blue" ], "B" : [ "red", "blue", "green" ] }
  4. { "_id" : 4, "A" : [ "red", "blue" ], "B" : [ "green", "red" ] }
  5. { "_id" : 5, "A" : [ "red", "blue" ], "B" : [ ] }
  6. { "_id" : 6, "A" : [ "red", "blue" ], "B" : [ [ "red" ], [ "blue" ] ] }
  7. { "_id" : 7, "A" : [ "red", "blue" ], "B" : [ [ "red", "blue" ] ] }
  8. { "_id" : 8, "A" : [ ], "B" : [ ] }
  9. { "_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:

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

The operation returns the following results:

  1. { "A" : [ "red", "blue" ], "B" : [ "red", "blue" ], "inBOnly" : [ ] }
  2. { "A" : [ "red", "blue" ], "B" : [ "blue", "red", "blue" ], "inBOnly" : [ ] }
  3. { "A" : [ "red", "blue" ], "B" : [ "red", "blue", "green" ], "inBOnly" : [ "green" ] }
  4. { "A" : [ "red", "blue" ], "B" : [ "green", "red" ], "inBOnly" : [ "green" ] }
  5. { "A" : [ "red", "blue" ], "B" : [ ], "inBOnly" : [ ] }
  6. { "A" : [ "red", "blue" ], "B" : [ [ "red" ], [ "blue" ] ], "inBOnly" : [ [ "red" ], [ "blue" ] ] }
  7. { "A" : [ "red", "blue" ], "B" : [ [ "red", "blue" ] ], "inBOnly" : [ [ "red", "blue" ] ] }
  8. { "A" : [ ], "B" : [ ], "inBOnly" : [ ] }
  9. { "A" : [ ], "B" : [ "red" ], "inBOnly" : [ "red" ] }