Brock
Brock

Reputation: 71

mongodb find duplicates in array across documents

Having an array of emails on a document. How would we find another document in the same collection that shares at least one email in common?

Essentially we have a contacts collection and each contact document has an array of emailAddresses[]. We want to make sure no two contact documents have an email in common with another document, but we're unable to find where this is happening.

Upvotes: 4

Views: 1662

Answers (1)

Parshuram Kalvikatte
Parshuram Kalvikatte

Reputation: 1646

db.collection.aggregate([
{"$unwind" : "$emails"},
{$group  : {"_id" : "$emails" , "count" :{"$sum" : 1} }},
{"$match" : {"count" : {"$gt" : 1}}}
])

This will result emails which are dupicate

Upvotes: 6

Related Questions