0
0
MongoDBquery~5 mins

createIndex method in MongoDB

Choose your learning style9 modes available
Introduction

The createIndex method helps speed up searches in a MongoDB collection by organizing data for quick lookup.

When you want to find documents faster by a specific field, like searching users by email.
When you need to enforce uniqueness on a field, such as usernames or product codes.
When you want to sort query results quickly by a certain field.
When you want to improve performance of frequent queries on large collections.
Syntax
MongoDB
db.collection.createIndex({ field: 1 or -1 }, options)

Use 1 for ascending order and -1 for descending order.

options is optional and can include settings like unique: true.

Examples
Creates an ascending index on the email field to speed up searches.
MongoDB
db.users.createIndex({ email: 1 })
Creates a descending index on the price field to speed up sorting by price from high to low.
MongoDB
db.products.createIndex({ price: -1 })
Creates a unique index on username to prevent duplicate usernames.
MongoDB
db.users.createIndex({ username: 1 }, { unique: true })
Sample Program

This command creates an ascending index on the lastName field in the customers collection to make searches by last name faster.

MongoDB
db.customers.createIndex({ lastName: 1 })
OutputSuccess
Important Notes

Creating indexes can take time on large collections, so plan accordingly.

Indexes use extra storage space but improve query speed.

Use unique indexes to enforce data rules like no duplicate emails.

Summary

createIndex makes searches faster by organizing data.

You can create ascending or descending indexes on fields.

Unique indexes prevent duplicate values in a field.