Unique index behavior in MongoDB - Time & Space Complexity
When using a unique index in MongoDB, it is important to understand how the time to check for duplicates grows as the data grows.
We want to know how the cost of enforcing uniqueness changes when more documents exist.
Analyze the time complexity of inserting a document with a unique index on a field.
// Create a unique index on the "email" field
db.users.createIndex({ email: 1 }, { unique: true })
// Insert a new user document
db.users.insertOne({ name: "Alice", email: "alice@example.com" })
This code creates a unique index on the email field and inserts a new user, which requires checking the index for duplicates.
When inserting, MongoDB must check the unique index to ensure no duplicate email exists.
- Primary operation: Searching the unique index for the email value.
- How many times: Once per insert operation.
The unique index is a balanced tree structure, so searching it grows slowly as data grows.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 4 steps |
| 100 | About 7 steps |
| 1000 | About 10 steps |
Pattern observation: The number of steps grows slowly, adding only a few more checks as data grows.
Time Complexity: O(log n)
This means checking for duplicates takes a little more time as the collection grows, but it grows slowly and efficiently.
[X] Wrong: "Checking for duplicates with a unique index takes the same time no matter how many documents exist."
[OK] Correct: The unique index uses a tree structure, so the time to check grows slowly with more data, not instantly constant.
Understanding how unique indexes work helps you explain database efficiency and data integrity in real projects.
"What if the unique index was on multiple fields instead of one? How would the time complexity change?"
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
