Created
April 7, 2023 08:03
-
-
Save SZharkov/36ee540e46713a485104353a2ad11de9 to your computer and use it in GitHub Desktop.
Remove duplicates in MongoDB with mongoose
This file contains hidden or 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.table.aggregate([ | |
| { | |
| "$group": { | |
| _id: {slug: "$slug"}, | |
| slugs: { $addToSet: "$_id" } , | |
| count: { $sum : 1 } | |
| } | |
| }, | |
| { | |
| "$match": { | |
| count: { "$gt": 1 } | |
| } | |
| } | |
| ]).forEach(function(doc) { | |
| doc.slugs.shift(); | |
| db.table.remove({ | |
| _id: {$in: doc.slugs} | |
| }); | |
| }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment