Introduction to MongoDB collection.createIndexes() Method

The createIndexes() method in MongoDB is used to create one or more indexes in a collection. Unlike the createIndex() method, createIndexes() can create multiple indexes at once. Indexes can improve query efficiency and speed up data retrieval.

Syntax

db.collection.createIndexes(indexes, options)

The parameters are:

  • indexes: One or more indexes to create.
  • options: An optional parameter object that specifies some options.

Use Cases

When multiple indexes need to be created in a collection, createIndexes() can be used instead of using createIndex() one by one. In addition, createIndexes() can create different types of indexes and set various options to control the behavior of the index.

Example

Assume we have a collection named sales containing the following documents:

{ "_id" : ObjectId("61f9ba9c11d1286dd56c40c1"), "product" : "apple", "quantity" : 100, "price" : 1.99 }
{ "_id" : ObjectId("61f9ba9c11d1286dd56c40c2"), "product" : "banana", "quantity" : 200, "price" : 0.99 }
{ "_id" : ObjectId("61f9ba9c11d1286dd56c40c3"), "product" : "orange", "quantity" : 300, "price" : 2.99 }

Now, we can use the createIndexes() method to create multiple indexes in the sales collection:

db.sales.createIndexes([
  { product: 1 },
  { quantity: -1 },
  { price: 1, quantity: -1 }
])

This will create three indexes based on the product, quantity, and price+quantity fields, with the product and price fields sorted in ascending order and the quantity field sorted in descending order.

Conclusion

The createIndexes() method can create one or more indexes in a collection, and various options can be set to control the behavior of the index. When multiple indexes need to be created, using createIndexes() can be more convenient than creating indexes one by one.