MongoDB Aggregation Set Operator - $setIntersection
MongoDB: $setIntersection
The MongoDB $setIntersection operators takes two or more arrays and returns a set of array with elements that appear in all of the input sets.
Syntax:
{ $setIntersection: [ <array1>, <array2>, ... ] }
- The $setIntersection operator can only performs set operation on arrays and treated as sets. If any duplicate value contains in an array, it ignores by $setIntersection operator. The order of the elements in not important in this operation..
- Only the unique value in an array appears as a result after filtering the duplicates values in the operation.
- When a set contains a nested array element, the $setIntersection 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: $setIntersection
The following aggregation operation uses the $setIntersection operator compares the array A and B returns an array set that contain the common array elements.
> db.test_collection.aggregate(
... [
... { $project: { A: 1, B: 1, commonToBoth: { $setIntersection: [ "$A", "$B" ] }, _id: 0 } }
... ]
... );
After the operation, following result will be returned by the $setIntersection operator.
> db.test_collection.aggregate(
... [
... { $project: { A: 1, B: 1, commonToBoth: { $setIntersection: [ "$A", "$B" ] }, _id: 0 } }
... ]
... );
{ "A" : [ "cat", "rat" ], "B" : [ "cat", "rat" ], "commonToBoth" : [ "cat", "rat" ] }
{ "A" : [ "cat", "rat" ], "B" : [ ], "commonToBoth" : [ ] }
{ "A" : [ ], "B" : [ "cat" ], "commonToBoth" : [ ] }
{ "A" : [ "cat", "rat" ], "B" : [ "rat", "cat", "rat" ], "commonToBoth" : [ "cat", "rat" ] }
{ "A" : [ "cat", "rat" ], "B" : [ "cat", "rat", "dog" ], "commonToBoth" : [ "cat", "rat" ] }
{ "A" : [ "cat", "rat" ], "B" : [ [ "cat", "rat" ] ], "commonToBoth" : [ ] }
{ "A" : [ "cat", "rat" ], "B" : [ [ "cat" ], [ "rat" ] ], "commonToBoth" : [ ] }
{ "A" : [ ], "B" : [ ], "commonToBoth" : [ ] }
{ "A" : [ "cat", "rat" ], "B" : [ "dog", "cat" ], "commonToBoth" : [ "cat" ] }
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-setintersection-operator.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics