$setEquals (aggregation)

Definition

  • $setEquals

New in version 2.6.

Compares two or more arrays and returns true if they have thesame distinct elements and false otherwise.

$setEquals has the following syntax:

  1. { $setEquals: [ <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

$setEquals performs set operation on arrays, treating arraysas sets. If an array contains duplicate entries, $setEqualsignores the duplicate entries. $setEquals ignores the order ofthe elements.

If a set contains a nested array element, $setEquals does not descendinto the nested array but evaluates the array at top-level.

Example Result
{ $setEquals: [ [ "a", "b", "a" ], [ "b", "a" ] ] } true
{ $setEquals: [ [ "a", "b" ], [ [ "a", "b" ] ] ] } false

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 $setEquals operator todetermine if the A array and the B arraycontain the same elements:

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

The operation returns the following results:

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