Problem Statement
Which method is used to create an index in MongoDB?
Explanation
The createIndex method is used to create indexes in MongoDB. You specify the field or fields to index and the sort order. A value of 1 creates an ascending index, while negative 1 creates a descending index.
Creating indexes is crucial for query performance. Without indexes, MongoDB must scan every document in a collection to find matches, which is slow for large collections. Indexes allow MongoDB to quickly locate documents using a B-tree data structure.
Code Solution
SolutionRead Only
// Create single-field index
db.users.createIndex({ email: 1 })
// Create descending index
db.products.createIndex({ price: -1 })
// Create compound index
db.orders.createIndex({ userId: 1, orderDate: -1 })