MONGODB Tutorial



MongoDB CreateIndex()


๐Ÿ“Œ MongoDB createIndex()

The createIndex() method in MongoDB is used to create an index on a specified field or fields in a collection. Indexes enhance search performance and are essential for optimizing query operations.

โœ… Basic Syntax

db.collection.createIndex({ field: 1 })
  

1 = Ascending Order, -1 = Descending Order

๐Ÿ”น Example: Create Index on "username"

db.users.createIndex({ username: 1 })
  

๐Ÿ”น Compound Index (Multiple Fields)

Useful when querying with multiple fields.

db.users.createIndex({ username: 1, age: -1 })
  

๐Ÿ” Unique Index

Prevents duplicate values in a field.

db.users.createIndex({ email: 1 }, { unique: true })
  

๐Ÿงน Dropping an Index

db.users.dropIndex({ username: 1 })
  
Tip: Use db.collection.getIndexes() to view all existing indexes.

๐ŸŒŸ Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review