Created
February 10, 2017 04:01
-
-
Save nguyenbathanh/475afeda579b8059efb4e0c6a758cf50 to your computer and use it in GitHub Desktop.
Mongodb how to remove duplicate entries in arrays
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
| // http://codingtricks.fidibuy.com/participant/join/5474b4eab7606ef9d71c045a/MongoDb:-how-to-remove-duplicate-entries-in-arrays | |
| // with modification | |
| // MongoDB GUI Tools: https://studio3t.com/download | |
| var fixFieldName = "primary_images"; | |
| var collectionName = "my_collection"; | |
| db[collectionName].find({ | |
| "_id": ObjectId("5762a2d397694a5295176697") | |
| }).forEach(function(elem) { | |
| var newArrays = []; | |
| var newArraysMap = {}; | |
| for (var i = 0; i < elem[fixFieldName].length; i++) { | |
| if (!newArraysMap[elem[fixFieldName][i]]) { | |
| newArraysMap[elem[fixFieldName][i]] = elem[fixFieldName][i]; | |
| newArrays.push(elem[fixFieldName][i]); | |
| } | |
| } | |
| elem[fixFieldName] = newArrays; | |
| db[collectionName].save(elem); | |
| printjson(elem); | |
| }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment