Q1. What is an index in MongoDB?
An index is a data structure that improves the speed of read operations (find, sort, etc.) by storing a small portion of the collection's data in an efficient traversal form. Indexes are created on fields and can be single-field, compound, or multi-key. They also support uniqueness constraints.
Q2. How do you create an index?
Use createIndex() on a collection:
db.users.createIndex({ email: 1 }, { unique: true })
db.users.createIndex({ age: -1, name: 1 })
The number indicates direction (1 ascending, -1 descending). Options like unique, sparse, or partial can be specified.Q3. How do you view existing indexes?
Use getIndexes():
db.users.getIndexes()
This returns an array of all indexes on the collection, including the default _id index.Q4. What is a compound index?
A compound index is an index on multiple fields. The order of fields matters:
db.users.createIndex({ age: 1, name: 1 })
This index supports queries on age, and on age + name together. It does not efficiently support queries on name alone.Q5. How do you drop an index?
Use dropIndex() with the index name or specification:
db.users.dropIndex("email_1")
db.users.dropIndex({ age: -1 })
To drop all indexes except _id, use dropIndexes().