Navigation
This version will reach end of life on Feb 2018. To upgrade, go to the Learn more about upgrading your version of MongoDB.

$setEquals (aggregation)

On this page

Definition

$setEquals

New in version 2.6.

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

$setEquals has the following syntax:

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

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

If a set contains a nested array element, $setEquals does not descend into 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:

{ "_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 $setEquals operator to determine if the A array and the B array contain the same elements:

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

The operation returns the following results:

{ "A" : [ "red", "blue" ], "B" : [ "red", "blue" ], "sameElements" : true }
{ "A" : [ "red", "blue" ], "B" : [ "blue", "red", "blue" ], "sameElements" : true }
{ "A" : [ "red", "blue" ], "B" : [ "red", "blue", "green" ], "sameElements" : false }
{ "A" : [ "red", "blue" ], "B" : [ "green", "red" ], "sameElements" : false }
{ "A" : [ "red", "blue" ], "B" : [ ], "sameElements" : false }
{ "A" : [ "red", "blue" ], "B" : [ [ "red" ], [ "blue" ] ], "sameElements" : false }
{ "A" : [ "red", "blue" ], "B" : [ [ "red", "blue" ] ], "sameElements" : false }
{ "A" : [ ], "B" : [ ], "sameElements" : true }
{ "A" : [ ], "B" : [ "red" ], "sameElements" : false }