A unique index makes sure that no two records in a database have the same value in certain fields. This helps keep data clean and avoids mistakes.
Unique index behavior in MongoDB
db.collection.createIndex({ fieldName: 1 }, { unique: true })db.users.createIndex({ email: 1 }, { unique: true })db.products.createIndex({ sku: 1 }, { unique: true })db.customers.createIndex({ phoneNumber: 1 }, { unique: true })This example creates a 'users' collection, adds two users, then creates a unique index on 'username'. It tries to insert a third user with a duplicate username 'alice', which causes an error.
use testdb // Create collection and insert sample data db.users.insertMany([ { _id: 1, username: "alice" }, { _id: 2, username: "bob" } ]) // Create unique index on username db.users.createIndex({ username: 1 }, { unique: true }) // Try to insert a duplicate username try { db.users.insertOne({ _id: 3, username: "alice" }) } catch (e) { print(e.message) }
Unique indexes prevent duplicate values but allow multiple documents with a missing (null) value unless sparse option is used.
Trying to insert a duplicate value on a unique index causes an error and the insert fails.
Unique indexes improve query speed on the indexed field while enforcing uniqueness.
Unique indexes keep data values unique in a collection.
They help avoid mistakes like duplicate emails or IDs.
Trying to add duplicates causes errors, protecting your data.
Practice
unique index in MongoDB?Solution
Step 1: Understand unique index function
A unique index prevents duplicate values in the indexed field across documents.Step 2: Compare options
Only To ensure no two documents have the same value for the indexed field describes this behavior correctly; others describe unrelated features.Final Answer:
To ensure no two documents have the same value for the indexed field -> Option AQuick Check:
Unique index = no duplicates [OK]
- Thinking unique index speeds queries without restrictions
- Confusing unique index with data compression
- Believing unique index allows duplicates
email in MongoDB?Solution
Step 1: Recall MongoDB syntax for unique index
The correct syntax usescreateIndexwith{ unique: true }option.Step 2: Evaluate options
db.collection.createIndex({ email: 1 }, { unique: true }) matches the correct syntax. db.collection.createIndex({ email: 1 }, { duplicate: false }) uses invalid optionduplicate. db.collection.createUniqueIndex({ email: 1 }) uses a non-existent method. db.collection.ensureIndex({ email: 1 }, { unique: false }) sets unique to false, which is incorrect.Final Answer:
db.collection.createIndex({ email: 1 }, { unique: true }) -> Option CQuick Check:
Use createIndex with unique:true [OK]
- Using wrong option name like 'duplicate'
- Using non-existent methods like createUniqueIndex
- Setting unique to false by mistake
username, what happens if you run this insert twice?db.users.insertOne({ username: "alice" })Solution
Step 1: Understand unique index effect on inserts
A unique index onusernameprevents duplicate values in that field.Step 2: Predict behavior on duplicate insert
The first insert succeeds. The second insert with the same username causes a duplicate key error and fails.Final Answer:
The second insert will fail with a duplicate key error -> Option BQuick Check:
Duplicate insert with unique index = error [OK]
- Assuming duplicates are allowed
- Thinking second insert overwrites first
- Believing MongoDB ignores unique index
email but still see duplicate emails in your collection. What is the most likely cause?Solution
Step 1: Understand unique index creation behavior
If duplicates exist before creating a unique index, MongoDB will fail to create it unless duplicates are removed or ignored.Step 2: Analyze why duplicates remain
If the index was forced or created without validation, duplicates remain. The unique index was created after duplicates already existed explains this scenario. The unique index was created with the wrong field name would cause index creation failure. MongoDB does not enforce uniqueness on indexes is false. The collection is empty is irrelevant.Final Answer:
The unique index was created after duplicates already existed -> Option AQuick Check:
Existing duplicates block unique index enforcement [OK]
- Assuming MongoDB ignores duplicates silently
- Not checking field name correctness
- Thinking empty collection causes duplicates
user.email in documents where user.active is true only. How can you create a unique index for this condition?Solution
Step 1: Understand partial unique index
A partial unique index applies uniqueness only to documents matching a filter condition.Step 2: Apply partial index to user.email where user.active is true
Create a partial unique index with filter { 'user.active': true } on field user.email correctly creates a partial unique index onuser.emailwith filter{ 'user.active': true }. Create a unique index on user.email without any filter enforces uniqueness on all documents. Create a compound unique index on user.email and user.active without filter enforces uniqueness on combined fields but not conditional. Create a unique index on user.active only is unrelated.Final Answer:
Create a partial unique index with filter { 'user.active': true } on field user.email -> Option DQuick Check:
Partial unique index = conditional uniqueness [OK]
- Creating unique index without filter for conditional uniqueness
- Using compound index without filter
- Indexing wrong field only
Ready to prove it?
Pass the test and this pattern moves unknown
