- 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
MongoDB aggregation group and remove duplicate array values?
Use MongoDB aggregate for this and within that, use $group. Let us create a collection with documents −
> db.demo649.insertOne( ... { "_id" : 101, "Names" : [ "John", "Bob", "Bob", "Robert" ], "CountryName" : "US" } ... ); { "acknowledged" : true, "insertedId" : 101 } > > db.demo649.insertOne({ "_id" :102, "Names" : [ "John", "Robert" ], "CountryName" : "UK"}); { "acknowledged" : true, "insertedId" : 102 }
Display all documents from a collection with the help of find() method −
> db.demo649.find();
This will produce the following output −
{ "_id" : 101, "Names" : [ "John", "Bob", "Bob", "Robert" ], "CountryName" : "US" } { "_id" : 102, "Names" : [ "John", "Robert" ], "CountryName" : "UK" }
Following is the query for aggregation group −
> db.demo649.aggregate( ... { $unwind : "$Names"}, ... { $group : { _id : "$_id" , Names : { $addToSet : "$Names" } , ... CountryName : { $first : "$CountryName" }}} ... )
This will produce the following output −
{ "_id" : 102, "Names" : [ "Robert", "John" ], "CountryName" : "UK" } { "_id" : 101, "Names" : [ "Robert", "Bob", "John" ], "CountryName" : "US" }
Advertisements