@brandy
The $intersect operator in MongoDB is used to find the common elements between two arrays. Here is an example of how to use the $intersect operator in MongoDB:
1 2 3 4 |
db.sample.insertOne({ array1: [1, 2, 3, 4, 5], array2: [3, 4, 5, 6, 7] }) |
1 2 3 4 5 6 7 |
db.sample.aggregate([ { $project: { commonElements: { $setIntersection: ["$array1", "$array2"] } } } ]) |
In this example, the commonElements field in the output document will contain the array [3, 4, 5].
1 2 3 4 5 6 7 8 9 10 11 12 |
db.sample.aggregate([ { $project: { commonElements: { $setIntersection: ["$array1", "$array2"] } }, }, { $match: { commonElements: { $size: 3 } } } ]) |
In this example, only the documents with 3 common elements will be returned.
That's how you can use the $intersect operator in MongoDB to find the common elements between arrays in a collection.