$setIsSubset (aggregation)
On this page
Definition
$setIsSubset
Takes two arrays and returns
true
when the first array is a subset of the second, including when the first array equals the second array, andfalse
otherwise.$setIsSubset
has the following syntax:{ $setIsSubset: [ <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
$setIsSubset
performs set operation on arrays, treating arrays
as sets. If an array contains duplicate entries, $setIsSubset
ignores the duplicate entries. $setIsSubset
ignores the order of
the elements.
If a set contains a nested array element, $setIsSubset
does not descend
into the nested array but evaluates the array at top-level.
Example | Result | |
---|---|---|
| true | |
| false |
Example
Consider an flowers
collection with the following documents:
db.flowers.insertMany( [ { "_id" : 1, "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ "rose", "orchid" ] }, { "_id" : 2, "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ "orchid", "rose", "orchid" ] }, { "_id" : 3, "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ "rose", "orchid", "jasmine" ] }, { "_id" : 4, "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ "jasmine", "rose" ] }, { "_id" : 5, "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ ] }, { "_id" : 6, "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ [ "rose" ], [ "orchid" ] ] }, { "_id" : 7, "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ [ "rose", "orchid" ] ] }, { "_id" : 8, "flowerFieldA" : [ ], "flowerFieldB" : [ ] }, { "_id" : 9, "flowerFieldA" : [ ], "flowerFieldB" : [ "rose" ] } ] )
The following operation uses the $setIsSubset
operator to
determine if the flowerFieldA
array is a subset of the flowerFieldB
array:
db.flowers.aggregate( [ { $project: { flowerFieldA:1, flowerFieldB: 1, AisSubset: { $setIsSubset: [ "$flowerFieldA", "$flowerFieldB" ] }, _id:0 } } ] )
The operation returns the following results:
{ "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ "rose", "orchid" ], "AisSubset" : true } { "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ "orchid", "rose", "orchid" ], "AisSubset" : true } { "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ "rose", "orchid", "jasmine" ], "AisSubset" : true } { "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ "jasmine", "rose" ], "AisSubset" : false } { "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ ], "AisSubset" : false } { "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ [ "rose" ], [ "orchid" ] ], "AisSubset" : false } { "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ [ "rose", "orchid" ] ], "AisSubset" : false } { "flowerFieldA" : [ ], "flowerFieldB" : [ ], "AisSubset" : true } { "flowerFieldA" : [ ], "flowerFieldB" : [ "rose" ], "AisSubset" : true }