0
0
MongoDBquery~5 mins

Why advanced indexing matters in MongoDB

Choose your learning style9 modes available
Introduction

Advanced indexing helps MongoDB find data faster. It makes your database work quicker and saves time.

When you have a large collection and want to speed up searches.
When you query data using multiple fields often.
When you want to sort results quickly by certain fields.
When you want to enforce uniqueness on some data fields.
When you want to improve performance of complex queries.
Syntax
MongoDB
db.collection.createIndex({ field1: 1, field2: -1 }, { unique: true })

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

The options object can include settings like unique to prevent duplicate values.

Examples
Creates a simple ascending index on the age field to speed up queries filtering by age.
MongoDB
db.users.createIndex({ age: 1 })
Creates a compound index on customerId ascending and orderDate descending to speed up queries filtering by customer and sorting by date.
MongoDB
db.orders.createIndex({ customerId: 1, orderDate: -1 })
Creates a unique index on sku to ensure no two products have the same SKU.
MongoDB
db.products.createIndex({ sku: 1 }, { unique: true })
Sample Program

This example inserts some books, creates a compound index on author ascending and year descending, then finds books by "Author 1" sorted by year descending. The index helps MongoDB do this quickly.

MongoDB
db.books.insertMany([
  { title: "Book A", author: "Author 1", year: 2020 },
  { title: "Book B", author: "Author 2", year: 2019 },
  { title: "Book C", author: "Author 1", year: 2021 }
])
db.books.createIndex({ author: 1, year: -1 })
db.books.find({ author: "Author 1" }).sort({ year: -1 })
OutputSuccess
Important Notes

Indexes speed up read queries but can slow down writes because the index must be updated.

Use indexes wisely on fields you query often to get the best performance.

Summary

Advanced indexing makes data searches faster and more efficient.

Compound and unique indexes help with complex queries and data integrity.

Proper indexing balances query speed and write performance.