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.
db.collection.createIndex({ field: 1 })
1
= Ascending Order, -1
= Descending Order
db.users.createIndex({ username: 1 })
Useful when querying with multiple fields.
db.users.createIndex({ username: 1, age: -1 })
Prevents duplicate values in a field.
db.users.createIndex({ email: 1 }, { unique: true })
db.users.dropIndex({ username: 1 })
db.collection.getIndexes()
to view all existing indexes.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!