- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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" }
- Related Articles
- Sort and Group in one MongoDB aggregation query?
- How to match and group array elements with the max value in MongoDB aggregation?
- How to remove duplicate values inside a list in MongoDB?
- MongoDB aggregation framework with group query example?
- How to remove duplicate property values in array – JavaScript?
- How to group nested fields in MongoDB aggregation with count value in array?
- MongoDB query to group duplicate documents
- MongoDB Aggregation to slice array inside array
- Coalesce values from different properties into a single array with MongoDB aggregation
- MongoDB query to group several fields using aggregation framework?
- MongoDB aggregation with equality inside array?
- MongoDB aggregation and projection?
- MongoDB transaction & indexes for duplicate values
- Is it possible to rename _id field after MongoDB group aggregation?
- Python - Remove duplicate values from a Pandas DataFrame

Advertisements