w3resource

MongoDB Aggregation Set Operator - $setEquals

MongoDB: $setEquals

The MongoDB $setEquals operators compare between two or more arrays and returns true if they have the same distinct elements otherwise it returns false.

Syntax:

{ $setEquals: [ <expression1>, <expression2> ... ] }
  • The $setEquals operator in MongoDB performs set operation on arrays, the arrays provided in the operator retreated as sets. The duplicate entries in an array, ignore by the $setEquals operator. $setEquals ignores the order of the elements.
  • If there is a nested array element in a set, the $setEquals operator does not descend into the nested array but evaluates the array at top-level.

Sample collection test_collection

{ "_id" : 1, "A" : [ "cat", "rat" ], "B" : [ "cat", "rat" ] }
{ "_id" : 2, "A" : [ "cat", "rat" ], "B" : [ ] }
{ "_id" : 3, "A" : [ ], "B" : [ "cat" ] }
{ "_id" : 4, "A" : [ "cat", "rat" ], "B" : [ "rat", "cat", "rat" ] }
{ "_id" : 5, "A" : [ "cat", "rat" ], "B" : [ "cat", "rat", "dog" ] }
{ "_id" : 6, "A" : [ "cat", "rat" ], "B" : [ [ "cat", "rat" ] ] }
{ "_id" : 7, "A" : [ "cat", "rat" ], "B" : [ [ "cat" ], [ "rat" ] ] }
{ "_id" : 8, "A" : [ ], "B" : [ ] }
{ "_id" : 9, "A" : [ "cat", "rat" ], "B" : [ "dog", "cat" ] }
}

Example: $setEquals

The following aggregation operation uses the $setEquals operator compares the array A and B to determine whether the arrays contain the same elements:

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

After the operation, following result will be returned by the $setEquals operator.

> db.test_collection.aggregate(
...    [
...      { $project: { A: 1, B: 1, sameElements: { $setEquals: [ "$A", "$B" ] }, _id: 0 } }
...    ]
... );
{ "A" : [ "cat", "rat" ], "B" : [ "cat", "rat" ], "sameElements" : true }
{ "A" : [ "cat", "rat" ], "B" : [ ], "sameElements" : false }
{ "A" : [ ], "B" : [ "cat" ], "sameElements" : false }
{ "A" : [ "cat", "rat" ], "B" : [ "rat", "cat", "rat" ], "sameElements" : true }
{ "A" : [ "cat", "rat" ], "B" : [ "cat", "rat", "dog" ], "sameElements" : false }
{ "A" : [ "cat", "rat" ], "B" : [ [ "cat", "rat" ] ], "sameElements" : false }
{ "A" : [ "cat", "rat" ], "B" : [ [ "cat" ], [ "rat" ] ], "sameElements" : false }
{ "A" : [ ], "B" : [ ], "sameElements" : true }
{ "A" : [ "cat", "rat" ], "B" : [ "dog", "cat" ], "sameElements" : false }

Previous: $out
Next: $setIntersection



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/mongodb/aggregation/mongodb-aggregatrion-setequals-operator.php