0
0
MongodbHow-ToBeginner · 3 min read

How to Create Index in MongoDB: Syntax and Examples

To create an index in MongoDB, use the db.collection.createIndex() method specifying the fields to index and their sort order. For example, db.users.createIndex({ name: 1 }) creates an ascending index on the name field.
📐

Syntax

The basic syntax to create an index in MongoDB is:

  • db.collection.createIndex(keys, options)

Here, keys is an object specifying the fields to index and their sort order (1 for ascending, -1 for descending). options is optional and can specify index type, uniqueness, and more.

mongodb
db.collection.createIndex({ field1: 1, field2: -1 }, { unique: true })
💻

Example

This example creates an ascending index on the username field in the users collection. It helps queries that filter or sort by username run faster.

mongodb
use mydatabase

db.users.createIndex({ username: 1 })
Output
{ "createdCollectionAutomatically" : false, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }
⚠️

Common Pitfalls

Common mistakes when creating indexes include:

  • Not specifying the correct sort order (1 or -1) for fields.
  • Creating duplicate indexes that already exist, which wastes space.
  • Forgetting to set unique: true when a unique constraint is needed.
  • Creating too many indexes, which can slow down writes.

Always check existing indexes with db.collection.getIndexes() before creating new ones.

mongodb
/* Wrong: missing sort order */
db.users.createIndex({ username: "asc" })

/* Right: use 1 for ascending */
db.users.createIndex({ username: 1 })
📊

Quick Reference

CommandDescription
db.collection.createIndex({ field: 1 })Create ascending index on field
db.collection.createIndex({ field: -1 })Create descending index on field
db.collection.createIndex({ field: 1 }, { unique: true })Create unique index
db.collection.getIndexes()List all indexes on collection
db.collection.dropIndex(indexName)Remove an index by name

Key Takeaways

Use db.collection.createIndex() with field and sort order to create indexes.
Specify 1 for ascending and -1 for descending index order.
Check existing indexes before creating new ones to avoid duplicates.
Use unique: true option to enforce unique values in an index.
Avoid creating too many indexes to keep write performance optimal.