Skip to content

Instantly share code, notes, and snippets.

@erancihan
Created March 16, 2021 16:51
Show Gist options
  • Save erancihan/a3967983da0df9eb8f465081fb3d8303 to your computer and use it in GitHub Desktop.
Save erancihan/a3967983da0df9eb8f465081fb3d8303 to your computer and use it in GitHub Desktop.
MongoDB Drop Duplicate entries
db.MyCollection.aggregate([
{
$group: {
_id: "$col",
duplicates: { $addToSet: "$_id" },
count: { $sum: 1 },
},
},
{ $match: { count: { $gt: 1 } } },
])
.toArray()
.forEach(function (doc) {
doc.duplicates.shift();
db.MyCollection.remove({ _id: { $in: doc.duplicates } });
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment