Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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
-
$matchfilters documents with specific IDs -
$groupcombines matched documents and extracts array values -
$setIntersectionfinds 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.
Advertisements
