Unique Check in MongoDB

Introduction

Sometimes in MongoDB, we may need a field that should contain only unique values. That means duplicate values are not allowed for a particular field throughout the collection. Such situations can happen often. For example, suppose there is a database that contains the details about all the employees working in a particular field. Each document has five fields – name, employee_id, age, location and of course, the automatically created _id field. Name, age and location can be the same for multiple employees, but the employee_id of every employee is always unique. To make sure that every document inserted into the collection should have a unique employee_id, we must set some kind of unique check on the employee_id. In this article, we will discuss how to perform unique checks in MongoDB.

Unique indexes

Every time we create a document in MongoDB, we always have an automatically created _id field. This field denotes a unique id for the document. But when we manually want to set a unique check on a field or a combination of fields, we use unique indexes. Let’s see how can we use unique indexes.

> db.details.find()
{ "_id" : ObjectId("5d667a43f849ba8866dd24ca"), "employee_id" : "0001", "name" : "Max", "age" : 25, "location" : "New York" }
>

We have a details collection and there is one document inside it. The document contains the employee_id, name, age, location and _id field. No unique indexes have been created yet. So what will happen if we insert another document with an existing employee_id? Let’ see.

> db.details.insert({"employee_id" : "0001", "name" : "John", "age": 21, "location": "Texas"})
WriteResult({ "nInserted" : 1 })
>

The insert operation works even the employee_id was the same as the last document. This happens because, by default, there is no unique index in any field. We have to create unique indexes manually. So let’s create a unique index on the employee_id field. But first, we have to delete one of the two documents because the employee_id is the same in both documents.

> db.details.deleteOne({name: "John"})
{ "acknowledged" : true, "deletedCount" : 1 }
> db.details.find()
{ "_id" : ObjectId("5d667a43f849ba8866dd24ca"), "employee_id" : "0001", "name" : "Max", "age" : 25, "location" : "New York" }
>

Now it’s fine. Let create a unique index for the employee_id field.

> db.details.createIndex({"employee_id": 1}, { unique:true})
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "ok" : 1
}
>

This is how we create a unique index in MongoDB by using the createIndex method. The createIndex method has two parameters – first is the name of the field, set to 0 and second is the unique option set to true. Let’s try to insert a document with existing employee_id now.

> db.details.insert({"employee_id" : "0001", "name" : "John", "age": 21, "location": "Texas"})
WriteResult({
        "nInserted" : 0,
        "writeError" : {
                "code" : 11000,
                "errmsg" : "E11000 duplicate key error collection: demoDB.details index: employee_id_1 dup key: { : "0001" }"
        }
})
>

We tried to insert a document with employee_id “0001”. A document with similar employee_id already exists in the collection. This is why the insert operation failed. Observe the error message.

"errmsg" : "E11000 duplicate key error collection: demoDB.details index: employee_id_1 dup key: { : "0001" }"

This happened because we set a unique index on the employee_id field. Let’s see what happens when we add a document with a unique employee_id.

> db.details.insert({"employee_id" : "0002", "name" : "John", "age": 21, "location": "Texas"})
WriteResult({ "nInserted" : 1 })
>

This time, the employee_id is “0002” and the document gets inserted.

Unique indexes on combination of fields

In MongoDB, we can also set unique indexes on a combination of fields. Suppose we want all the documents in our collection should have a unique combination of name and location. If there exists a document with the name “Lisa” and location “Texas”, we can’t add any further document that has name field as “Lisa” and location field as “Texas”.

Let’s see how can we create such unique indexes.

> db.details.createIndex({"name": 1, "location": 1}, { unique:true})
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "ok" : 1
}
>

We just have to pass the fields in the first parameter on whom we want to apply the unique index. The details collection already has a field with the name “Lisa” and location “Texas”. Let’s try to add one more document with such values.

> db.details.insert({"employee_id" : "0002", "name" : "Lisa", "age": 24, "location": "Texas"})
WriteResult({
        "nInserted" : 0,
        "writeError" : {
                "code" : 11000,
                "errmsg" : "E11000 duplicate key error collection: demoDB.details index: name_1_location_1 dup key: { : "Lisa", : "Texas" }"
        }
})
>

Yes, it shows an error because we already applied a unique index on the combination of name and location field.

Conclusion

The unique check is used in almost every database present. It is very helpful in maintaining databases. MongoDB provides unique indexes to apply unique checks. We can apply a unique index on a single field or a combination of fields.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.