Skip to content

Instantly share code, notes, and snippets.

@nguyenbathanh
Created February 10, 2017 04:01
Show Gist options
  • Select an option

  • Save nguyenbathanh/475afeda579b8059efb4e0c6a758cf50 to your computer and use it in GitHub Desktop.

Select an option

Save nguyenbathanh/475afeda579b8059efb4e0c6a758cf50 to your computer and use it in GitHub Desktop.
Mongodb how to remove duplicate entries in arrays
// 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