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



You can use $setIntersection for this. Let us first create a collection with documents −

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

Following is the query to display all documents from a collection with the help of find() method −

> db.setInterSectionDemo.find().pretty();

This will produce the following output −

{ "_id" : 101, "Value1" : [ 55, 67, 89 ] } { "_id" : 102, "Value2" : [ 90, 45, 55 ] } { "_id" : 103, "Value3" : [ 92, 67, 45 ]

Here is the query to find intersection of sets between the documents in a single collection in MongoDB −

> 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 ...       } ...    } ... ]);

This will produce the following output −

{ "firstValue" : [ 55, 67, 89 ], "secondValue" : [ 92, 67, 45 ], "CommonValue" : [ 67 ] }
Updated on: 2019-07-30T22:30:26+05:30

191 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements