Navigation

$setIntersection (aggregation)

On this page

Definition

$setIntersection

New in version 2.6.

Takes two or more arrays and returns an array that contains the elements that appear in every input array.

$setIntersection has the following syntax:

{ $setIntersection: [ <array1>, <array2>, ... ] }

The arguments can be any valid expression as long as they each resolve to an array. For more information on expressions, see Expressions.

Behavior

$setIntersection performs set operation on arrays, treating arrays as sets. If an array contains duplicate entries, $setIntersection ignores the duplicate entries. $setIntersection ignores the order of the elements.

$setIntersection filters out duplicates in its result to output an array that contain only unique entries. The order of the elements in the output array is unspecified.

If a set contains a nested array element, $setIntersection does not descend into the nested array but evaluates the array at top-level.

Example   Result
{ $setIntersection: [ [ "a", "b", "a" ], [ "b", "a" ] ] }   [ "b", "a" ]
{ $setIntersection: [ [ "a", "b" ], [ [ "a", "b" ] ] ] }   [ ]

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 $setIntersection operator to return an array of elements common to both the A array and the B array:

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

The operation returns the following results:

{ "A" : [ "red", "blue" ], "B" : [ "red", "blue" ], "commonToBoth" : [ "blue", "red" ] }
{ "A" : [ "red", "blue" ], "B" : [ "blue", "red", "blue" ], "commonToBoth" : [ "blue", "red" ] }
{ "A" : [ "red", "blue" ], "B" : [ "red", "blue", "green" ], "commonToBoth" : [ "blue", "red" ] }
{ "A" : [ "red", "blue" ], "B" : [ "green", "red" ], "commonToBoth" : [ "red" ] }
{ "A" : [ "red", "blue" ], "B" : [ ], "commonToBoth" : [ ] }
{ "A" : [ "red", "blue" ], "B" : [ [ "red" ], [ "blue" ] ], "commonToBoth" : [ ] }
{ "A" : [ "red", "blue" ], "B" : [ [ "red", "blue" ] ], "commonToBoth" : [ ] }
{ "A" : [ ], "B" : [ ], "commonToBoth" : [ ] }
{ "A" : [ ], "B" : [ "red" ], "commonToBoth" : [ ] }