MongoDB Unique Index Practice Questions with Solutions

Introduction

A Unique Index in MongoDB ensures that a field cannot contain duplicate values. It is especially useful for fields such as email addresses, usernames, employee IDs, or product codes where every value should be different. In this chapter, you will practice creating unique indexes, testing duplicate values, checking indexes, and removing them using practical MongoDB queries. MongoDB Unique Index practice questions with solutions help to understand the concepts.

Q1. Create a Unique Index on the Email Field

Problem Statement

Create a unique index on the email field in the students collection so that two students cannot have the same email address.

MongoDB Command / Query

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

Expected Output

email_1

Explanation

The unique: true option tells MongoDB that every indexed email value must be unique.


Q2. Insert a Student with a Unique Email

Problem Statement

Insert a student with an email address that does not already exist.

MongoDB Command / Query

db.students.insertOne({
  name: "Rahul",
  age: 17,
  email: "rahul@example.com"
})

Expected Output

{
  acknowledged: true,
  insertedId: ObjectId("...")
}

Explanation

The email is unique, so MongoDB allows the document to be inserted.


Q3. Try to Insert a Duplicate Email

Problem Statement

Try to insert another student using the same email address.

MongoDB Command / Query

db.students.insertOne({
  name: "Aman",
  age: 16,
  email: "rahul@example.com"
})

Expected Output

E11000 duplicate key error

Explanation

The email already exists in the collection. Because email has a unique index, MongoDB rejects the new document.


Q4. Create a Unique Index on a Username

Problem Statement

Create a unique index on the username field so that every user must have a different username.

MongoDB Command / Query

db.users.createIndex(
  { username: 1 },
  { unique: true }
)

Expected Output

username_1

Explanation

MongoDB will prevent duplicate values in the username field.


Q5. Test the Unique Username Rule

Problem Statement

Insert two users with different usernames.

MongoDB Command / Query

db.users.insertMany([
  {
    username: "rahul17",
    name: "Rahul"
  },
  {
    username: "neha16",
    name: "Neha"
  }
])

Expected Output

{
  acknowledged: true,
  insertedIds: {
    "0": ObjectId("..."),
    "1": ObjectId("...")
  }
}

Explanation

Both usernames are different, so MongoDB accepts both documents.


Q6. Find the Unique Indexes in a Collection

Problem Statement

Display all indexes created on the users collection.

MongoDB Command / Query

db.users.getIndexes()

Expected Output

[
  {
    name: "_id_",
    key: { _id: 1 }
  },
  {
    name: "username_1",
    key: { username: 1 },
    unique: true
  }
]

Explanation

getIndexes() displays the indexes available on the collection. The unique: true property identifies a unique index.


Q7. Create a Unique Index on an Employee ID

Problem Statement

Create a unique index on employeeId so that every employee has a different ID.

MongoDB Command / Query

db.employees.createIndex(
  { employeeId: 1 },
  { unique: true }
)

Expected Output

employeeId_1

Explanation

MongoDB will not allow two documents to have the same employeeId.


Q8. Try to Insert Duplicate Employee IDs

Problem Statement

Insert an employee and then try to insert another employee with the same employeeId.

MongoDB Command / Query

db.employees.insertOne({
  employeeId: 101,
  name: "Ravi"
})

Then:

db.employees.insertOne({
  employeeId: 101,
  name: "Priya"
})

Expected Output

First command:

{
  acknowledged: true,
  insertedId: ObjectId("...")
}

Second command:

E11000 duplicate key error

Explanation

The second document uses an employeeId that already exists, so the unique index prevents the insertion.


Q9. Create a Unique Index with a Custom Name

Problem Statement

Create a unique index on the phone field and give the index a custom name.

MongoDB Command / Query

db.customers.createIndex(
  { phone: 1 },
  {
    unique: true,
    name: "unique_phone_index"
  }
)

Expected Output

unique_phone_index

Explanation

The name option allows you to choose a meaningful name for the index. The unique: true option prevents duplicate phone values.


Q10. Remove a Unique Index

Problem Statement

Remove the unique index named unique_phone_index from the customers collection.

MongoDB Command / Query

db.customers.dropIndex("unique_phone_index")

Expected Output

{
  nIndexesWas: 2,
  ok: 1
}

Explanation

dropIndex() removes the specified index. After removing the unique index, MongoDB will no longer enforce uniqueness through that index.

Important: MongoDB’s default _id index cannot be removed because every document must have a unique _id.

Key Takeaways

  • A unique index prevents duplicate values in an indexed field.
  • Use { unique: true } when creating a unique index.
  • Common uses include email, username, employeeId, and phone.
  • MongoDB returns an E11000 duplicate key error when a duplicate indexed value is inserted.
  • getIndexes() displays the indexes of a collection.
  • You can give an index a custom name using the name option.
  • dropIndex() removes a specific index.
  • The default _id index is automatically created by MongoDB and cannot be dropped.
  • Unique indexes are useful for enforcing data integrity.

FAQs

1. What is a Unique Index in MongoDB?

A Unique Index ensures that the indexed field does not contain duplicate values across documents.

2. How do you create a Unique Index in MongoDB?

Use createIndex() with the unique: true option:

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

3. What happens when a duplicate value is inserted into a Unique Index?

MongoDB rejects the operation and normally returns an E11000 duplicate key error.

4. Can multiple fields have Unique Indexes?

Yes. You can create unique indexes on different fields, such as email, username, and employeeId.

5. How can I check whether an index is unique?

Use:

db.collection.getIndexes()

A unique index will contain:

unique: true

6. Can a Unique Index have a custom name?

Yes. You can specify a custom name using the name option:

db.users.createIndex(
  { username: 1 },
  {
    unique: true,
    name: "unique_username"
  }
)

7. Can the default _id index be deleted?

No. MongoDB automatically creates the _id index, and it cannot be dropped while the collection uses the standard _id field.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top