How to get the intersection of two arrays in MongoDB?


To get intersection of two arrays, use $setIntersection along with aggregate(). 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();

This will produce the following output −

{
   "_id" : ObjectId("5e286e28cfb11e5c34d8992a"),
   "Values1" : [
      10,
      20,
      30,
      40,
      50
   ],
   "Values2" : [
      30,
      100,
      70,
      120,
      40
   ]
}

Following is the query to get the intersection of two arrays in MongoDB −

> db.demo61.aggregate(
...    [
...       { $project: { BothValues:{ $setIntersection: [ "$Values1", "$Values2" ] }} }
...    ]
... );

This will produce the following output −

{ "_id" : ObjectId("5e286e28cfb11e5c34d8992a"), "BothValues" : [ 30, 40 ] }

Updated on: 03-Apr-2020

544 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements