← Back to MongoDB Course | Chapter 8: Indexes | Lesson 2 of 7

createIndex()

createIndex builds an index on one or more fields, ascending or descending.

In this page:

  1. createIndex()
Syntax
javascript
db.collection_name.createIndex({ field: 1 })
db.collection_name.createIndex({ field: 1 }, { unique: true })

createIndex()

db.collection.createIndex({ field: 1 }) creates an ascending index (-1 for descending, which rarely matters for single fields).

Options include unique to forbid duplicates, sparse and partial to index only some documents, and expireAfterSeconds for TTL indexes. Index builds on large collections use resources, so plan them.

Note: A unique index also enforces data integrity, such as unique emails.

Example: createIndex()

bash
test> db.users.createIndex({ email: 1 }, { unique: true })
email_1
test> db.users.insertMany([{ email: "[email protected]" }, { email: "[email protected]" }])
MongoBulkWriteError: E11000 duplicate key error collection: shop.users index: email_1 dup key: { email: "[email protected]" }
test> db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 })
createdAt_1

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
Common Mistakes
  1. Creating duplicate indexes
  2. Forgetting unique when needed
  3. Building large indexes at peak load
Chapter Summary
  • createIndex({ field: 1 })
  • unique forbids duplicates
  • partial and sparse index subsets
  • TTL indexes expire documents
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.