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" }

Updated on: 12-May-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements