How to use intersect operator in mongodb?

Member

by brandy , in category: MySQL , 4 months ago

How to use intersect operator in mongodb?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by elise_daugherty , 4 months ago

@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. Create a sample collection with arrays:
1
2
3
4
db.sample.insertOne({ 
  array1: [1, 2, 3, 4, 5],
  array2: [3, 4, 5, 6, 7]
})


  1. Use the $project stage with $setIntersection to find the common elements between the two arrays:
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. You can also use $match stage to filter documents with specific common elements:
 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.

Related Threads:

How to use like operator in PostgreSQL?
How to use not like operator in PostgreSQL?
How to use the instanceof operator in PHP?
How to use the ternary operator in PHP?
How to use like operator in mysql?
How to use ternary operator in vue.js?