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 get the intersection of two arrays in MongoDB?
To get intersection of two arrays in MongoDB, use $setIntersection along with aggregate(). This operator returns an array containing elements that appear in both input arrays.
Syntax
db.collection.aggregate([
{
$project: {
fieldName: { $setIntersection: ["$array1", "$array2"] }
}
}
]);
Sample Data
Let us create a collection with documents ?
db.demo61.insertOne({
"Values1": [10, 20, 30, 40, 50],
"Values2": [30, 100, 70, 120, 40]
});
{
"acknowledged": true,
"insertedId": ObjectId("5e286e28cfb11e5c34d8992a")
}
Display all documents from a collection with the help of find() method ?
db.demo61.find().pretty();
{
"_id": ObjectId("5e286e28cfb11e5c34d8992a"),
"Values1": [
10,
20,
30,
40,
50
],
"Values2": [
30,
100,
70,
120,
40
]
}
Example
Following is the query to get the intersection of two arrays in MongoDB ?
db.demo61.aggregate([
{
$project: {
BothValues: { $setIntersection: ["$Values1", "$Values2"] }
}
}
]);
{ "_id": ObjectId("5e286e28cfb11e5c34d8992a"), "BothValues": [30, 40] }
Key Points
-
$setIntersectionremoves duplicates and returns unique elements present in both arrays. - The order of elements in the result may not match the original arrays.
- Works with arrays containing any BSON data types.
Conclusion
Use $setIntersection with the aggregation framework to find common elements between two arrays. This operator efficiently returns the intersection as a new array field in your projection.
Advertisements
