0
0
MongoDBquery~5 mins

Unique index behavior in MongoDB

Choose your learning style9 modes available
Introduction

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.

When you want to make sure each user has a unique email address in your app.
When you need to prevent duplicate product codes in an inventory system.
When storing social security numbers or IDs that must be unique for each person.
When you want to avoid duplicate entries in a list of registered vehicles.
When ensuring unique usernames in a website's login system.
Syntax
MongoDB
db.collection.createIndex({ fieldName: 1 }, { unique: true })
The '1' means the index is created in ascending order.
The 'unique: true' option enforces uniqueness on the field.
Examples
This creates a unique index on the 'email' field in the 'users' collection to prevent duplicate emails.
MongoDB
db.users.createIndex({ email: 1 }, { unique: true })
This ensures that each product's SKU is unique in the 'products' collection.
MongoDB
db.products.createIndex({ sku: 1 }, { unique: true })
This prevents two customers from having the same phone number in the 'customers' collection.
MongoDB
db.customers.createIndex({ phoneNumber: 1 }, { unique: true })
Sample Program

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.

MongoDB
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)
}
OutputSuccess
Important Notes

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.

Summary

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.