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.
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.
Let's look at some examples of how to use the createIndex
method in the programGuru
collection in MongoDB:
db.programGuru.createIndex({ name: 1 })
This command creates an ascending index on the name
field in the programGuru
collection.
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.
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.
Let's go through a complete example that includes switching to a database, creating a collection, inserting documents, and creating indexes.
This step involves switching to a database named myDatabase
.
use myDatabase
In this example, we switch to the myDatabase
database.
This step involves creating a new collection named programGuru
in the myDatabase
database.
db.createCollection("programGuru")
Here, we create a collection named programGuru
.
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.
This step involves using the createIndex
method to create indexes in the programGuru
collection.
db.programGuru.createIndex({ name: 1 })
We create an ascending index on the name
field.
db.programGuru.createIndex({ name: 1, age: -1 })
We create a compound index on the name
field (ascending) and the age
field (descending).
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.
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.