Fix This Page
Navigation

$setIsSubset (aggregation)

On this page

Definition

$setIsSubset

New in version 2.6.

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, and false 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
{ $setIsSubset: [ [ "a", "b", "a" ], [ "b", "a" ] ] }   true
{ $setIsSubset: [ [ "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 $setIsSubset operator to determine if the A array is a subset of the B array:

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

The operation returns the following results:

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