How to get data of array intersection in MongoDB?


For array interection in MongoDB, use the $setIntersection in aggregate(). Let us create a collection with documents −

> db.demo625.insertOne(
...    {
...       Name: "John",
...       Marks: [56,98,60]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9ab8e16c954c74be91e6aa")
}
> db.demo625.insertOne(
...    {
...       Name: "John",
...       Marks: [110,56,72]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9ab8e26c954c74be91e6ab")
}
> db.demo625.insertOne(
...    {
...       Name: "Chris",
...       Marks: [90,91]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9ab8e26c954c74be91e6ac")
}
> db.demo625.insertOne(
...    {
...       Name: "Robert",
...       Marks: [60,75]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9ab8e26c954c74be91e6ad")
}

Display all documents from a collection with the help of find() method −

> db.demo625.find();

This will produce the following output −

{ "_id" : ObjectId("5e9ab8e16c954c74be91e6aa"), "Name" : "John", "Marks" : [ 56, 98, 60 ] }
{ "_id" : ObjectId("5e9ab8e26c954c74be91e6ab"), "Name" : "John", "Marks" : [ 110, 56, 72 ] }
{ "_id" : ObjectId("5e9ab8e26c954c74be91e6ac"), "Name" : "Chris", "Marks" : [ 90, 91 ] }
{ "_id" : ObjectId("5e9ab8e26c954c74be91e6ad"), "Name" : "Robert", "Marks" : [ 60, 75 ] }

Following is the query to get data of array intersection in MongoDB −

> db.demo625.aggregate([
...
...
...    { "$project": {
...       "Name": 1,
...       "Marks": {
...          "$setIntersection": [ "$Marks", [56,98,60] ]
...       }
...    }}
... ])

This will produce the following output −

{ "_id" : ObjectId("5e9ab8e16c954c74be91e6aa"), "Name" : "John", "Marks" : [ 56, 60, 98 ] }
{ "_id" : ObjectId("5e9ab8e26c954c74be91e6ab"), "Name" : "John", "Marks" : [ 56 ] }
{ "_id" : ObjectId("5e9ab8e26c954c74be91e6ac"), "Name" : "Chris", "Marks" : [ ] }
{ "_id" : ObjectId("5e9ab8e26c954c74be91e6ad"), "Name" : "Robert", "Marks" : [ 60 ] }

Updated on: 12-May-2020

309 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements