How to perform intersection of sets between the documents in a single collection in MongoDB?

To find the intersection of sets between documents in a single MongoDB collection, use the $setIntersection operator within an aggregation pipeline. This operator returns an array containing elements that appear in all specified arrays.

Syntax

{
    $project: {
        "result": {
            $setIntersection: ["$array1", "$array2", "$array3", ...]
        }
    }
}

Sample Data

db.setInterSectionDemo.insertMany([
    {"_id": 101, "Value1": [55, 67, 89]},
    {"_id": 102, "Value2": [90, 45, 55]},
    {"_id": 103, "Value3": [92, 67, 45]}
]);
{
    "acknowledged": true,
    "insertedIds": {
        "0": 101,
        "1": 102,
        "2": 103
    }
}

View the inserted documents ?

db.setInterSectionDemo.find();
{ "_id": 101, "Value1": [55, 67, 89] }
{ "_id": 102, "Value2": [90, 45, 55] }
{ "_id": 103, "Value3": [92, 67, 45] }

Example: Find Common Elements Between Two Documents

Find the intersection between documents with IDs 101 and 103 ?

db.setInterSectionDemo.aggregate([
    {
        "$match": {
            "_id": { "$in": [101, 103] }
        }
    },
    {
        "$group": {
            "_id": 0,
            "firstValue": { "$first": "$Value1" },
            "secondValue": { "$last": "$Value3" }
        }
    },
    {
        "$project": {
            "firstValue": 1,
            "secondValue": 1,
            "CommonValue": { "$setIntersection": ["$firstValue", "$secondValue"] },
            "_id": 0
        }
    }
]);
{ "firstValue": [55, 67, 89], "secondValue": [92, 67, 45], "CommonValue": [67] }

How It Works

  • $match filters documents with specific IDs
  • $group combines matched documents and extracts array values
  • $setIntersection finds common elements between the arrays

Conclusion

Use $setIntersection in aggregation pipelines to find common elements between array fields across documents. Group the documents first, then apply set intersection to compare their array values.

Updated on: 2026-03-15T00:58:25+05:30

248 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements