0% completed
In MongoDB, an index is a data structure that improves the speed of data retrieval operations on a collection. Indexes are crucial for efficient querying and can significantly enhance the performance of read operations. Without indexes, MongoDB must perform a collection scan, which examines every document in a collection to select those that match the query statement. This can be very slow for large datasets.
Indexes support the efficient execution of queries by providing quick access to documents. They store a portion of the data set in a structure that is easy to traverse, which reduces the number of documents that MongoDB needs to scan to fulfill a query.
To create an index in MongoDB, you use the createIndex()
method. The basic syntax for creating an index is:
db.collection.createIndex( { <field1>: <type1>, <field2>: <type2>, ... }, { <option1>: <value1>, <option2>: <value2>, ... } )
1
for ascending order or -1
for descending order.First, let's insert some documents into the products
collection to work with:
db.products.insertMany([ { name: "Apple", category: "Fruit", price: 1.2 }, { name: "Carrot", category: "Vegetable", price: 0.8 }, { name: "Banana", category: "Fruit", price: 1.1 }, { name: "Broccoli", category: "Vegetable", price: 1.5 }, { name: "Grapes", category: "Fruit", price: 2.0 } ])
Create an index on the name
field in ascending order.
db.products.createIndex({ name: 1 })
Explanation:
db.products.createIndex({ name: 1 })
: This command creates an index on the name
field in ascending order. This index will speed up queries that filter or sort by the name
field.Create a unique index on the name
field and specify a name for the index.
db.products.createIndex( { name: 1 }, { unique: true, name: "uniqueNameIndex" } )
Explanation:
db.products.createIndex({ name: 1 }, { unique: true, name: "uniqueNameIndex" })
: This command creates a unique index on the name
field. The index enforces the uniqueness of the name
field and is named "uniqueNameIndex".Create a compound index on the category
and price
fields.
db.products.createIndex({ category: 1, price: -1 })
Explanation:
db.products.createIndex({ category: 1, price: -1 })
: This command creates a compound index on the category
field in ascending order and the price
field in descending order. This index will speed up queries that filter or sort by both category
and price
.products
collection by name
, an index on the name
field can significantly speed up these queries.products
collection by price
, an index on the price
field can make these sorts much faster.name
field ensures that each product has a unique name.Creating indexes in MongoDB is a fundamental technique to enhance query performance and ensure efficient data retrieval. By understanding how to create single field and compound indexes, and utilizing optional parameters to customize index behavior, you can optimize your database operations and improve the responsiveness of your applications.
.....
.....
.....