Bird
Raised Fist0
MongoDBquery~20 mins

Unique index behavior in MongoDB - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Unique Index Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate
2:00remaining
What happens when inserting duplicate values on a unique index?
Consider a MongoDB collection with a unique index on the field email. What will be the result of inserting a document with an email value that already exists in the collection?
MongoDB
db.users.createIndex({ email: 1 }, { unique: true });
db.users.insertOne({ name: "Alice", email: "alice@example.com" });
db.users.insertOne({ name: "Bob", email: "alice@example.com" });
AThe second insert will fail with a duplicate key error.
BThe second insert will be ignored silently.
CThe second insert will succeed and create a duplicate email.
DThe second insert will overwrite the first document.
Attempts:
2 left
💡 Hint
Unique indexes prevent duplicate values in the indexed field.
❓ query_result
intermediate
2:00remaining
What is the output of this query with a unique sparse index?
A collection has a unique sparse index on the field phone. The collection contains documents with and without the phone field. What will be the result of inserting two documents without the phone field?
MongoDB
db.contacts.createIndex({ phone: 1 }, { unique: true, sparse: true });
db.contacts.insertOne({ name: "John" });
db.contacts.insertOne({ name: "Jane" });
ABoth inserts fail because the unique index requires all documents to have the field.
BThe second insert fails with a duplicate key error.
CBoth inserts succeed because sparse indexes ignore documents missing the indexed field.
DOnly the first insert succeeds; the second is ignored.
Attempts:
2 left
💡 Hint
Sparse indexes only index documents that contain the indexed field.
📝 Syntax
advanced
2:00remaining
Which command correctly creates a unique compound index on fields username and email?
Select the valid MongoDB command to create a unique compound index on username and email fields.
Adb.users.createIndex(["username", "email"], { unique: true });
Bdb.users.createIndex({ username: 1, email: 1 }, { unique: true });
Cdb.users.createIndex({ username: 1 }, { email: 1, unique: true });
Ddb.users.createIndex({ username: 1, email: 1 }, unique = true);
Attempts:
2 left
💡 Hint
The index keys must be in an object with field names and sort order.
🔧 Debug
advanced
2:00remaining
Why does this unique index creation fail?
You try to create a unique index on the username field, but MongoDB returns an error. The collection already has documents with duplicate username values. What is the cause of the failure?
MongoDB
db.users.createIndex({ username: 1 }, { unique: true });
AUnique indexes cannot be created on string fields.
BThe syntax of createIndex is incorrect.
CThe database is in read-only mode.
DThe collection contains duplicate usernames, violating the unique index constraint.
Attempts:
2 left
💡 Hint
Unique indexes require all existing data to be unique on the indexed field.
🧠 Conceptual
expert
3:00remaining
How does a unique partial index differ from a unique sparse index in MongoDB?
Choose the correct statement about the difference between a unique partial index and a unique sparse index.
AA unique partial index enforces uniqueness only on documents matching a filter expression; a unique sparse index ignores documents missing the indexed field.
BA unique sparse index enforces uniqueness only on documents matching a filter expression; a unique partial index ignores documents missing the indexed field.
CBoth indexes behave the same and enforce uniqueness on all documents regardless of fields.
DUnique partial indexes allow duplicates; unique sparse indexes do not.
Attempts:
2 left
💡 Hint
Partial indexes use a filter expression; sparse indexes depend on field presence.

Practice

(1/5)
1. What is the main purpose of a unique index in MongoDB?
easy
A. To ensure no two documents have the same value for the indexed field
B. To speed up queries without any restrictions on data
C. To allow duplicate values but sort them quickly
D. To store data in a compressed format

Solution

  1. Step 1: Understand unique index function

    A unique index prevents duplicate values in the indexed field across documents.
  2. 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.
  3. Final Answer:

    To ensure no two documents have the same value for the indexed field -> Option A
  4. Quick Check:

    Unique index = no duplicates [OK]
Hint: Unique index means no duplicate values allowed [OK]
Common Mistakes:
  • Thinking unique index speeds queries without restrictions
  • Confusing unique index with data compression
  • Believing unique index allows duplicates
2. Which of the following is the correct way to create a unique index on the field email in MongoDB?
easy
A. db.collection.createUniqueIndex({ email: 1 })
B. db.collection.createIndex({ email: 1 }, { duplicate: false })
C. db.collection.createIndex({ email: 1 }, { unique: true })
D. db.collection.ensureIndex({ email: 1 }, { unique: false })

Solution

  1. Step 1: Recall MongoDB syntax for unique index

    The correct syntax uses createIndex with { unique: true } option.
  2. Step 2: Evaluate options

    db.collection.createIndex({ email: 1 }, { unique: true }) matches the correct syntax. db.collection.createIndex({ email: 1 }, { duplicate: false }) uses invalid option duplicate. db.collection.createUniqueIndex({ email: 1 }) uses a non-existent method. db.collection.ensureIndex({ email: 1 }, { unique: false }) sets unique to false, which is incorrect.
  3. Final Answer:

    db.collection.createIndex({ email: 1 }, { unique: true }) -> Option C
  4. Quick Check:

    Use createIndex with unique:true [OK]
Hint: Use createIndex with { unique: true } to enforce uniqueness [OK]
Common Mistakes:
  • Using wrong option name like 'duplicate'
  • Using non-existent methods like createUniqueIndex
  • Setting unique to false by mistake
3. Given a collection with a unique index on username, what happens if you run this insert twice?
db.users.insertOne({ username: "alice" })
medium
A. Both inserts succeed, creating two identical documents
B. The second insert will fail with a duplicate key error
C. The second insert overwrites the first document
D. MongoDB ignores the unique index and inserts both

Solution

  1. Step 1: Understand unique index effect on inserts

    A unique index on username prevents duplicate values in that field.
  2. 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.
  3. Final Answer:

    The second insert will fail with a duplicate key error -> Option B
  4. Quick Check:

    Duplicate insert with unique index = error [OK]
Hint: Duplicate insert on unique field causes error [OK]
Common Mistakes:
  • Assuming duplicates are allowed
  • Thinking second insert overwrites first
  • Believing MongoDB ignores unique index
4. You created a unique index on email but still see duplicate emails in your collection. What is the most likely cause?
medium
A. The unique index was created after duplicates already existed
B. The unique index was created with the wrong field name
C. MongoDB does not enforce uniqueness on indexes
D. The collection is empty

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    The unique index was created after duplicates already existed -> Option A
  4. Quick Check:

    Existing duplicates block unique index enforcement [OK]
Hint: Create unique index before duplicates exist [OK]
Common Mistakes:
  • Assuming MongoDB ignores duplicates silently
  • Not checking field name correctness
  • Thinking empty collection causes duplicates
5. You want to ensure uniqueness on user.email in documents where user.active is true only. How can you create a unique index for this condition?
hard
A. Create a compound unique index on user.email and user.active without filter
B. Create a unique index on user.email without any filter
C. Create a unique index on user.active only
D. Create a partial unique index with filter { 'user.active': true } on field user.email

Solution

  1. Step 1: Understand partial unique index

    A partial unique index applies uniqueness only to documents matching a filter condition.
  2. 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 on user.email with 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.
  3. Final Answer:

    Create a partial unique index with filter { 'user.active': true } on field user.email -> Option D
  4. Quick Check:

    Partial unique index = conditional uniqueness [OK]
Hint: Use partial unique index with filter for conditional uniqueness [OK]
Common Mistakes:
  • Creating unique index without filter for conditional uniqueness
  • Using compound index without filter
  • Indexing wrong field only
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard