MongoDB: How To Find Duplicate Documents In Collection

Looking out to find duplicate documents in a MongoDB collection? This article will help you find duplicate records in MongoDB collection by a specific field.

MongoDB is a JSON based document-oriented database that can handle big size of data without compromising the performance.

Find Duplicate Documents In MongoDB Collection

Sometimes you want to remove all the duplicate documents from a collection but you don’t know how to find them. Here we will see how to find duplicate records in MongoDB. Once you find the duplicates, you can easily remove those from Mongo collection.

For this example, I am using Github Public Issues API. I have fetched the issues from Github API and inserted them into the database by making same requests multiple times to make duplicates.

I will use aggregate method along with $group and $match pipeline operators to find duplicates. Let’s step by step implement code to get duplicates.

MongoDB Group Records by Field

First step towards implementing duplicate search is Grouping Records.

Above code fetches all the documents present in issues collection grouped by issue_number field.

MongoDB Get Duplicate Documents

It’s time to implement the complete query and get all the rows that have more than 1 count in MongoDB collection.

$addToSet operator adds a value to an array if the value is not already present. If the value is already present, it does nothing.

$sum calculates and returns the sum of numeric values.

$match applies condition on the result set. $gt will check if the count is greater than provided number (ie 1).

The above query produces following output.

Now you have ObjectId of all the duplicate records present in MongoDB collection. You can run a separate query to remove them.

Looking to insert and update records in MongoDB together? This will help you upsert documents in a single query.

Repair MongoDB instance after crash on Windows.

Conclusion

This article elaborates on how to find duplicate documents in MongoDB collection by a specific field.

TLDR;

  • Group records by the field on which you want to find duplicates
  • Add all the Object Ids to an array
  • Count the documents
  • Apply condition to fetch only documents that are available more than once in collection

Hope you find some value out of this article. If you liked the article, make sure to spread it across other developers. See you in next article 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *