Creating a Unique Index on MongoDB


We have implemented MongoDB on a number of past projects and continue to, as we are a MongoDB partner. We wanted to share some of the knowledge we’ve gained and pass along tutorials on how you can get the most out of MongoDB with your current or future projects. Check out this easy to follow tutorial on creating a unique index in MongoDB.

 Creating your unique index in MongoDB

MongoDB lets users specify between indexes and that prevents applications from duplicating values into inserted fields and a number of other issues that can possibly arise. However, MongoDB cannot make a unique index on specified index fiends if your collection already has data which would violate the unique index constraints.


Unique Indexes on a single field

In order to create a unique index, use the following:

db.collection.createIndex( { a: 1 }, { unique: true } )

For example, just say you're creating a unique index called "name-id" under the accounts collection so you avoid future multiples or duplicates per entity. Implement the following:

db.accounts.createIndex( { "name-id": 1 }, { unique: true } )

Since the _id index is a unique index you may also want to try using the "_id" field for data instead of continuing to use the unique index in different fields.


Unique compound index

It's also possible to create a unique constraint for compound indexes, this particular way of indexing creates a unique for the combination of index keys, not for each individual key. Check out the following:

db.collection.createIndex( { a: 1, b: 1 }, { unique: true } )

Unique Index and Missing Field

If there is no value for your fields, each index entry per item will be labeled as null for each index it is included it, which is why users may sometimes want to combine unique and sparse options. Sparse indexes are able to skip missed information instead of registering it as null, and unique indexes aren't able to carry duplicate values for fields. Check out the following code to remedy the issue:

db.collection.createIndex( { a: 1 }, { unique: true, sparse: true } )

Taking your App from Development to Deployment


Faster than Traditional Ops
Continuous Improvement
Cost Effective

Topics: DevOps