Find Duplicate Value Entries in MongoDB Collection
-
Without access to SQL, sometimes simple queries can be confusing in NoSQL systems. If we want to do a simple search in MongoDB to find duplicate values in a collection, it can be a little confusing.
In my example, we go through the "myCollection" collection and look for values in "field_to_search" that are duplicated at least once and list them. You need only change "myCollection" to the name of your collection and "field_to_search" to the name of the field that you want to check for duplicates and voila.
db.myCollection.aggregate([ {$group: { _id: "$field_to_search", count: { $sum: 1}}}, {$match: { count: { $gt: 1 }}}])
-
For more detail, showing the UIDs of each of the duplicates in question, try this little extension:
db.myCollection.aggregate([ {$group: { _id: "$field_to_search", "dups": { "$push": "$_id" }, count: { $sum: 1}}}, {$match: { count: { $gt: 1 }}}])