
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to remove duplicate values inside a list in MongoDB?
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" ] }
- Related Questions & Answers
- MongoDB aggregation group and remove duplicate array values?
- How to remove duplicate record in MongoDB 3.x?
- How to remove duplicate entries by two keys in MongoDB?
- Program to remove duplicate entries in a list in Python
- C# program to remove duplicate elements from a List
- How to remove duplicate property values in array – JavaScript?
- Python - Remove duplicate values from a Pandas DataFrame
- How to remove duplicate values from a MySQL table using LEFT JOIN?
- Program to remove duplicate entries in a linked list in Python
- How to remove NULL values from a list in R?
- Get the duplicate values of a field in MongoDB?
- Python - Remove duplicate values from a Pandas Data Frame
- List all duplicate values in a nested JavaScript object
- Python program to remove duplicate elements from a Circular Linked List
- MongoDB transaction & indexes for duplicate values
Advertisements