| by Arround The Web | No comments

How to Create a Unique Index in MongoDB

In MongoDB, a unique index ensures that each value in a particular field or group of fields inside a collection is unique. Using the createIndex() method, we can make a unique index field for the specific collection. For the purpose of maintaining the data integrity and avoiding duplicate entries in vital fields, unique indexes are helpful. The article covered the ways to create a unique index for the specific collection.

db.candidates.insertMany([

  { name: "Alexa Bill", grade: "A", course: "python"},

  { name: "Jane Marks", grade: "B", course: "java"},

  { name: "Pawel Ken", grade: "C", course: "C#"},

  { name: "Emily Jeo", grade: "D", course: "php"}

]);

We can also create a unique index field when the collection is present with some documents inside it. For this, we insert the document in the new collection which is “candidates” whose query for insertion is given as follows:

Example 1: Create a Unique Index of a Single Field

We can create the index using the createIndex() method and we can make that field unique by specifying the unique option with the Boolean “true”.

db.candidates.createIndex( { grade: 1 }, { unique: true } )

Here, we initiate the createIndex() method on the “candidates” collection to create a unique index of a specific field. Then, we provide the “grade” field with the value of “1” for the index specification. The value of “1” here represents the ascending index of the collection. Next, we specify the “unique” option with the “true” value to enforce the uniqueness of the field “grade”.

The output represents that the unique index on the “grade” field is created for the “candidates” collection:

Example 2: Create a Unique Index of More Than One Field

In the previous example, only a single field is created as a unique index. But we can also create two fields as a unique index simultaneously using the createIndex() method.

db.candidates.createIndex( { grade: 1, course: 1 }, { unique: true } )

Here, we call the createIndex() method on the same “candidates” collection. We specify two fields to the createIndex() method – “grade” and “course” – with the value of “1” as the first expression. Then, we set the unique option with the “true” value to create these two unique fields.

The output represents two unique indexes, “grade_1” and “course_1”, for the following “candidates” collection:

Example 3: Create a Compound Unique Index of the Fields

However, we can also create a unique compound index within the same collection simultaneously. We achieve this through the following query:

db.candidates.createIndex( { name: 1, grade: 1, course: 1 }, { unique: true }

We use the createIndex() method again to create the compound unique index for the “candidates” collection. This time, we pass three fields – “grade”, “name,” and “course” – which act as the ascending index fields for the “candidates” collection. Next, we call the “unique” option to make the field unique as “true” is assigned against that option.

The output displays the results which show that all three fields are now the unique index of the specified collection:

Example 4: Create a Unique Index of Duplicate Field Values

Now, we try to make the unique index for the duplicate field value which triggers an error to maintain the uniqueness constraint.

db.candidates.createIndex({name: 1},{unique:true})

Here, we apply the unique index criteria for the field that contains similar values. Inside the createIndex() method, we call the “name” field with the value of “1” to make it a unique index and define the unique option with the “true” value. As the two documents have the “name” field with identical values, we can’t make this field a unique index of the “candidates” collection. The duplicate key error is triggered upon the execution of the query.

As expected, the output generates the results because the name field has the same values for two different documents:

Thus, we update the “candidates” collection by giving a unique value to each “name” field in the document and then create the “name” field as the unique index. Executing that query generally creates the “name” field as the unique index as shown in the following:

Example 5: Create a Unique Index of a Missing Field

Alternatively, we apply the createIndex() method on the field that doesn’t exist in any of the documents of the collection. As a result, the index stores a null value against that field, and the operation fails due to a violation against the value of the field.

db.candidates.createIndex( { email: 1 }, { unique: true } )

Here, we employ the createIndex() method where the “email” field is provided with the value of “1”. The “email” field doesn’t exist in the “candidates” collection and we try to make it a unique index for the “candidates” collection by setting the unique option to “true”.

When the query for this is executed, we get the error in the output as the “email” field is missing in the “candidates” collection:

Example 6: Create a Unique Index of a Field with a Sparse Option

Next, the unique index can also be created with the sparse option. The functionality of a sparse index is that it only includes documents that have the indexed field, excluding the documents that do not have the indexed field. We provided the following structure to setup the sparse option:

db.candidates.createIndex( { course : 1 },

{ name: "unique_sparse_course_index", unique: true, sparse: true } )

Here, we provide the createIndex() method where the “course” field is set with the value of “1”. After that, we specify the additional option to set a unique index field which is “course”. The options include the “name” which sets the “unique_sparse_course_index” index. Then, we have the “unique” option which is specified with the “true” value and the “sparse” option is also set to “true”.

The output creates a unique and sparse index on the “course” field as shown in the following:

Example 7: Show the Created Unique Index Using the GetIndexes() Method

In the previous example, only a unique index was created for the provided collection. To view and get the information on the unique indexes for the “candidates” collection, we use the following getIndexes() method:

db.candidates.getIndexes();

Here, we call the getIndexes() function on the “candidates” collection. The getIndexes() function returns all the index fields for the “candidates” collection that we created in the previous examples.

The output displays the unique index that we created for the collection: either a unique index, compound index, or the unique sparse index:

Conclusion

We attempted to create a unique index for the specific fields of the collection. We explored the various ways to create a unique index for a single field and multiple fields. We also attempted to create a unique index where the operation fails due to a unique constraint violation.

Share Button

Source: linuxhint.com

Leave a Reply