How to Apply Unique Constraints in MongoDB

This article explains how to apply unique constraints in MongoDB.

Applying unique constraints

To apply a unique constraint in MongoDB, specify true for the unique option of createIndex() when creating an index.

The examples below show the cases of a single-key index and a compound-key index.

Single-key index

For a single-key index, you can create it by simply running the following code in the mongo shell.

> db.members.createIndex({ userId: 1 }, { unique: true })

Compound-key index

For a compound-key index, the code is the same as for a single-key index.

> db.members.createIndex({ firstname: 1, lastname: 1 }, { unique: true })

With a compound-key index, the combination of compound keys only needs to be unique, so the following can be set without issue.

> db.members.insert({ firstname: "kc", lastname: "Kim" })
> db.members.insert({ firstname: "et", lastname: "Kim" })
> db.members.insert({ firstname: "kc" })

Limits on setting unique constraints

As with relational databases, you cannot apply a unique constraint to a collection that already contains duplicate data. This may be obvious once duplicate data already exists.

Also, setting a unique constraint on a hashed index is not recommended. See Considerations for Hashed Indexes.

Behavior when no value is set for the unique constraint key

As in the example above where a unique constraint was set with a compound-key index, if there is a field with no value, MongoDB internally treats it as null.

For example, suppose there is a collection with a unique constraint on field x as follows.

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

Assume that data is inserted without specifying field x.

> db.collection.insert({ y: 1 })
WriteResult({ "nInserted" : 1 })

The first insert succeeds because x: null is assigned. What happens if another document without field x is inserted?

> db.collection.insert({ z: 1 })
WriteResult({
    "nInserted" : 0,
    "writeError" : {
        "code" : 11000,
        "errmsg" : "E11000 duplicate key error collection: test.collection index: x_1 dup key: { : null }"
    }
})

As shown above, an error occurs and the insert cannot be performed. The error message also shows that null is assigned when no value is specified.

References