0
0
MongoDBquery~30 mins

Index direction (ascending vs descending) in MongoDB - Hands-On Comparison

Choose your learning style9 modes available
Create and Use Ascending and Descending Indexes in MongoDB
📖 Scenario: You are managing a small online bookstore database. You want to speed up searches on book titles and prices by creating indexes. You will create one index that sorts titles in ascending order and another index that sorts prices in descending order.
🎯 Goal: Build MongoDB indexes on the books collection: one index on title in ascending order and another index on price in descending order.
📋 What You'll Learn
Create a books collection with three documents containing title and price fields.
Create a variable called titleIndex that defines an ascending index on the title field.
Create a variable called priceIndex that defines a descending index on the price field.
Create the ascending index on title using db.books.createIndex() with titleIndex.
Create the descending index on price using db.books.createIndex() with priceIndex.
💡 Why This Matters
🌍 Real World
Indexes are used in real databases to speed up searches and sorting, just like an index in a book helps you find pages quickly.
💼 Career
Database administrators and developers create and manage indexes to optimize application performance and handle large data efficiently.
Progress0 / 4 steps
1
DATA SETUP: Create the books collection with sample documents
Insert three documents into the books collection with these exact entries: { title: "The Hobbit", price: 15 }, { title: "1984", price: 12 }, and { title: "Brave New World", price: 18 }.
MongoDB
Need a hint?

Use db.books.insertMany() with an array of objects for the books.

2
CONFIGURATION: Define index variables for ascending and descending order
Create a variable called titleIndex that sets title to 1 for ascending order, and a variable called priceIndex that sets price to -1 for descending order.
MongoDB
Need a hint?

Use const to create the variables with the correct field and direction values.

3
CORE LOGIC: Create the ascending index on title
Use db.books.createIndex() with the variable titleIndex to create an ascending index on the title field.
MongoDB
Need a hint?

Call db.books.createIndex() with titleIndex as the argument.

4
COMPLETION: Create the descending index on price
Use db.books.createIndex() with the variable priceIndex to create a descending index on the price field.
MongoDB
Need a hint?

Call db.books.createIndex() with priceIndex as the argument.