w3resource

MongoDB Aggregation Set Operator - $setIsSubset

MongoDB: $setIsSubset

The MongoDB $setIsSubset operators take exactly two argument expressions i.e. two sets 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.

Syntax:

{ $setIsSubset: [ <expression1>, <expression2> ] }
  • The $setIsSubset operator can only performs set operation on arrays and treated as sets. If any duplicate value contains in an array, it ignores by $setIsSubset operator. The order of the elements in not important in this operation..
  • When a set contains a nested array element, the $setIsSubset 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: $setIsSubset

The following aggregation operation uses the $setIsSubset operator compares the array A and B to determine if the A array is a subset of the B array:

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

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

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

Previous: $setDifference
Next: $anyElementTrue



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-setissubset-operator.php