Getting unique values within two arrays in one MongoDB document


To get unique values within two arrays in a document, use a $setUnion in aggregate(). The $setUnion takes two or more arrays and returns an array containing the elements that appear in any input array.

Let us create a collection with documents −

>db.demo608.insertOne({"ListOfName1":["John","Chris","Bob","David"],"ListOfName2":["Bob", "Sam","John","Robert","Chris"]}
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e974542f57d0dc0b182d62b")
}

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

> db.demo608.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5e974542f57d0dc0b182d62b"),
   "ListOfName1" : [
      "John",
      "Chris",
      "Bob",
      "David"
   ],
   "ListOfName2" : [
      "Bob",
      "Sam",
      "John",
      "Robert",
      "Chris"
   ]
}

Following is the query to get unique values within two arrays in one MongoDB document −

> db.demo608.aggregate([
...    {$project:{SetOfNames:{$setUnion:['$ListOfName1','$ListOfName2']}}}
... ]).pretty();

This will produce the following output −

{
   "_id" : ObjectId("5e974542f57d0dc0b182d62b"),
   "SetOfNames" : [
      "Bob",
      "Chris",
      "David",
      "John",
      "Robert",
      "Sam"
   ]
}

Updated on: 15-May-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements