Skip to content

Instantly share code, notes, and snippets.

@saintc0d3r
Created June 27, 2014 18:00
Show Gist options
  • Save saintc0d3r/1e11d49f2b0790e47624 to your computer and use it in GitHub Desktop.
Save saintc0d3r/1e11d49f2b0790e47624 to your computer and use it in GitHub Desktop.
Add unique index while also remove the documents which has duplicated key index
// Let's say there is a fruits collection where it contains documents as follow
db.fruits.insert({'name':'pear'})
db.fruits.insert({'name':'apple'})
db.fruits.insert({'name':'pear'})
// Then, we want to prevent another document with name = pear can be inserted into fruits collection
// In the other words, we want to make the name property become unique.
// And also, duplicated document would be removed
db.fruits.ensureIndex({'name':1}, {'unique':true, 'dropDups':true})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment