 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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"    ] }Advertisements
 