Definition
$setEquals
Compares two or more arrays and returns
true
if they have the same distinct elements andfalse
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 | Notes |
---|---|---|
|
| The arrays do not contain the same elements. |
|
| The arrays do not contain the same elements. |
|
| Both arrays contain the same unique elements. When treated as sets, the first array is |
|
| The elements in the arrays are not equal. The first array contains the strings |
|
| The elements in the arrays are not equal. The first array is empty and the second array has two string elements. |
|
| The arrays do not contain the same unique elements. The first array only contains |
Example
Consider a bakeryOrders
collection with the following documents:
db.bakeryOrders.insertMany( [
{ _id: 0, cakes: ["chocolate", "vanilla"], cupcakes: ["chocolate", "vanilla"] },
{ _id: 1, cakes: ["chocolate", "vanilla"], cupcakes: ["vanilla", "chocolate"] },
{ _id: 2, cakes: ["chocolate", "chocolate"], cupcakes: ["chocolate"] },
{ _id: 3, cakes: ["vanilla"], cupcakes: ["chocolate"] },
{ _id: 4, cakes: ["vanilla"], cupcakes: [] }
] )
The following operation uses the $setEquals
operator to determine if the cakes
array and the cupcakes
array in each order contain the same flavors:
db.bakeryOrders.aggregate(
[
{
$project: {
_id: 0,
cakes: 1,
cupcakes: 1,
sameFlavors: { $setEquals: [ "$cakes", "$cupcakes" ] }
}
}
] )
Note
$project
The operation returns the following results:
{
cakes: [ "chocolate", "vanilla" ],
cupcakes: [ "chocolate", "vanilla" ],
sameFlavors: true
},
{
cakes: [ "chocolate", "vanilla" ],
cupcakes: [ "vanilla", "chocolate" ],
sameFlavors: true
},
{
cakes: [ "chocolate", "chocolate" ],
cupcakes: [ "chocolate" ],
sameFlavors: true
},
{
cakes: [ "vanilla" ],
cupcakes: [ "chocolate" ],
sameFlavors: false
},
{
cakes: [ "vanilla" ],
cupcakes: [],
sameFlavors: false
}