Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

1 Answer
Samual Sam

You can use aggregate framework along with $setUnion operator. Let us first create a collection with documents −

> db.removeDuplicatesDemo.insertOne({"InstructorName":"Chris","InstructorAge":34,"InstructorSubject":
   ["Java","C","Java","C++","MongoDB","MySQL","MongoDB"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cb9d96c895c4fd159f80807")
}

Following is the query to display all documents from the collection with the help of find() method −

> db.removeDuplicatesDemo.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cb9d96c895c4fd159f80807"),
   "InstructorName" : "Chris",
   "InstructorAge" : 34,
   "InstructorSubject" : [
      "Java",
      "C",
      "Java",
      "C++",
      "MongoDB",
      "MySQL",
      "MongoDB"
   ]
}

Following is the query to remove duplicate values inside a list in MongoDB −

> db.removeDuplicatesDemo.aggregate([
...    { "$project": {
...       "InstructorName":1,
...       "InstructorAge" :1,
...       "InstructorSubject" :{ "$setUnion": [ "$InstructorSubject", [] ] }
...    }}
... ]).pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cb9d96c895c4fd159f80807"),
   "InstructorName" : "Chris",
   "InstructorAge" : 34,
   "InstructorSubject" : [
      "C",
      "C++",
      "Java",
      "MongoDB",
      "MySQL"
   ]
}

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.