Background
To ensure there is no duplicate documents, we could create an unique index.
However, it will throw error when there are duplicates entries in the collection:
MongoDB cannot create a
unique index
on the specified index field(s) if the collection already contains data that would violate the unique constraint for the index.
Remove the duplicates by keys
1 | const collection = db.collection('MyCollection'); |
Create the unique index
1 | await collection.createIndex({ key1: 1, key2: 1 }, { unique: true, name: 'unique_index' }); |