- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Combining unique items from arrays in MongoDB?
To combine unique items from array, use aggregate() in MongoDB. Let us create a collection with documents −
> db.demo420.insert( ... { ... ... "details" : [ ... { ... "Value1":10, ... "Value2":20, ... "Value3":30 ... } ... ] ... } ... ) WriteResult({ "nInserted" : 1 }) > db.demo420.insert( ... { ... ... "Info" : [ ... { ... "Value1":10, ... "Value2":20, ... "Value3":300 ... } ... ] ... } ... ) WriteResult({ "nInserted" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo420.find();
This will produce the following output −
{ "_id" : ObjectId("5e739a569822da45b30346dc"), "details" : [ { "Value1" : 10, "Value2" : 20, "Value3" : 30 } ] } { "_id" : ObjectId("5e739a569822da45b30346dd"), "Info" : [ { "Value1" : 10, "Value2" : 20, "Value3" : 300 } ] }
Following is the query to combine unique items from arrays −
> db.demo420.aggregate([ ... { "$project": { ... "_id": 0, ... "unique": { ... "$filter": { ... "input": { ... "$setDifference": [ ... { "$concatArrays": [ ... "$Info.Value1", ... "$Info.Value2", ... "$Info.Value3" ... ... ]}, ... [] ... ] ... }, ... "cond": { "$ne": [ "$$this", "" ] } ... } ... } ... }}, ... { "$unwind": "$unique" }, ... { "$group": { ... "_id": null, ... "uniqueArray": { "$addToSet": "$unique" } ... }} ... ])
This will produce the following output −
{ "_id" : null, "uniqueArray" : [ 300, 20, 10 ] }
Advertisements