Skip to content

Instantly share code, notes, and snippets.

@saintc0d3r
Created June 27, 2014 14:33
Show Gist options
  • Save saintc0d3r/8640ff4b3e2f3c9000e0 to your computer and use it in GitHub Desktop.
Save saintc0d3r/8640ff4b3e2f3c9000e0 to your computer and use it in GitHub Desktop.
Unique Index on a mongodb's collection
// Let's say there is a fruits collection where it contains a pear document
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
db.fruits.ensureIndex({'name':1}, {'unique':true})
// Let's push a new document that has different name than to the existing one
db.fruits.insert({'name':'apel'})
// Then push another new document whose name is same as an existing document's in the collection
db.fruits.insert({'name':'pear'})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment