Created
March 16, 2021 16:51
-
-
Save erancihan/a3967983da0df9eb8f465081fb3d8303 to your computer and use it in GitHub Desktop.
MongoDB Drop Duplicate entries
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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