Introduction to MongoDB $setIntersection Operator

$setIntersection is an array operator in MongoDB that returns the intersection of two arrays. It can be used to operate on arrays within the aggregation pipeline.

Syntax

The syntax for the $setIntersection operator is as follows:

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

Here, <array1> and <array2> are the arrays to be compared.

Use Cases

The $setIntersection operator can be used in scenarios where you need to find the intersection of two arrays. For example, it can be used to find the common tags between two documents or to filter out documents that have an intersection with a given array in the aggregation pipeline.

Example

Suppose we have the following two documents representing the hobbies of two people:

{ "name": "Alice", "hobbies": ["swimming", "reading", "traveling"] }
{ "name": "Bob", "hobbies": ["swimming", "cooking", "reading"] }

We can use $setIntersection to find the hobbies that Alice and Bob have in common:

db.collection.aggregate([
  {
    $project: {
      commonHobbies: {
        $setIntersection: ["$hobbies", ["swimming", "reading"]]
      }
    }
  }
])

In the above aggregation pipeline, the $setIntersection operator returns the common hobbies between Alice and Bob, which are ["swimming", "reading"].

Conclusion

The $setIntersection operator is a convenient way in MongoDB to return the intersection of two arrays. It can be used within the aggregation pipeline to find the common elements between two documents or to filter out documents that have an intersection with a given array.