0
0
MongoDBquery~30 mins

Single field index in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
Create and Use a Single Field Index in MongoDB
📖 Scenario: You are managing a small online bookstore database. To improve search speed for books by their title, you want to create an index on the title field.
🎯 Goal: Create a MongoDB collection called books with sample book documents. Then create a single field index on the title field to speed up queries searching by book title.
📋 What You'll Learn
Create a books collection with 3 book documents having fields title, author, and year.
Create a variable called indexField and set it to the string "title".
Create a single field index on the title field using the indexField variable.
Verify the index creation by listing all indexes on the books collection.
💡 Why This Matters
🌍 Real World
Indexes in MongoDB help speed up searches on large collections, just like an index in a book helps you find pages quickly.
💼 Career
Database administrators and backend developers often create indexes to optimize query performance and improve application speed.
Progress0 / 4 steps
1
Create the books collection with sample data
Create a MongoDB collection called books and insert these exact documents: { title: "The Hobbit", author: "J.R.R. Tolkien", year: 1937 }, { title: "1984", author: "George Orwell", year: 1949 }, and { title: "To Kill a Mockingbird", author: "Harper Lee", year: 1960 }.
MongoDB
Need a hint?

Use db.books.insertMany([...]) with the exact documents listed.

2
Create a variable for the index field
Create a variable called indexField and set it to the string "title".
MongoDB
Need a hint?

Use const indexField = "title" to create the variable.

3
Create a single field index on the title field
Use the indexField variable to create a single field ascending index on the books collection.
MongoDB
Need a hint?

Use db.books.createIndex({ [indexField]: 1 }) to create the ascending index.

4
List all indexes on the books collection
List all indexes on the books collection to verify the index on the title field was created.
MongoDB
Need a hint?

Use db.books.getIndexes() to list all indexes.