MongoDB Create Index
MongoDB Create Index
In MongoDB, the createIndex operation is used to create indexes on collections. This method is essential for improving the performance of queries and ensuring efficient data retrieval within MongoDB collections.
Syntax
db.collection.createIndex(keys, options)
The createIndex method takes a keys parameter to specify the fields to index and an optional options parameter to customize the index creation.
Example MongoDB Create Index
Let's look at some examples of how to use the createIndex method in the programGuru collection in MongoDB:
1. Create a Single Field Index
db.programGuru.createIndex({ name: 1 })
This command creates an ascending index on the name field in the programGuru collection.
2. Create a Compound Index
db.programGuru.createIndex({ name: 1, age: -1 })
This command creates a compound index on the name field (ascending) and the age field (descending) in the programGuru collection.
3. Create a Unique Index
db.programGuru.createIndex({ email: 1 }, { unique: true })
This command creates a unique index on the email field in the programGuru collection, ensuring that all values in the email field are unique.
Full Example
Let's go through a complete example that includes switching to a database, creating a collection, inserting documents, and creating indexes.
Step 1: Switch to a Database
This step involves switching to a database named myDatabase.
use myDatabase
In this example, we switch to the myDatabase database.
Step 2: Create a Collection
This step involves creating a new collection named programGuru in the myDatabase database.
db.createCollection("programGuru")
Here, we create a collection named programGuru.
Step 3: Insert Documents into the Collection
This step involves inserting documents into the programGuru collection.
db.programGuru.insertMany([
{ name: "John Doe", age: 30, email: "john.doe@example.com" },
{ name: "Jane Smith", age: 25, email: "jane.smith@example.com" },
{ name: "Jim Brown", age: 35, email: "jim.brown@example.com" }
])
We insert multiple documents into the programGuru collection.
Step 4: Create Indexes in the Collection
This step involves using the createIndex method to create indexes in the programGuru collection.
Create a Single Field Index
db.programGuru.createIndex({ name: 1 })
We create an ascending index on the name field.

Create a Compound Index
db.programGuru.createIndex({ name: 1, age: -1 })
We create a compound index on the name field (ascending) and the age field (descending).

Create a Unique Index
db.programGuru.createIndex({ email: 1 }, { unique: true })
We create a unique index on the email field, ensuring that all values in the email field are unique.
Conclusion
The MongoDB createIndex operation is crucial for optimizing query performance and ensuring efficient data retrieval. Understanding how to create single field, compound, and unique indexes allows you to enhance the performance and scalability of your MongoDB applications.