0
0
MongoDBquery~30 mins

When not to index in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
When Not to Index in MongoDB
📖 Scenario: You are managing a MongoDB database for a small online bookstore. You want to understand when it is better not to create indexes on certain fields to keep the database efficient.
🎯 Goal: Learn to create a collection with sample book data, add a configuration variable to decide when to index, write conditional logic to create an index only if the document count is above the threshold, and finalize the collection setup without unnecessary indexes.
📋 What You'll Learn
Create a MongoDB collection named books with specific documents
Add a variable minIndexCount to decide the minimum number of documents before indexing
Write conditional logic to create an index on genre only if the number of documents is above minIndexCount
Ensure the collection does not have an index on genre if the document count is low
💡 Why This Matters
🌍 Real World
In real applications, creating indexes on small collections can waste storage and slow down writes. This project shows how to avoid unnecessary indexes.
💼 Career
Database administrators and backend developers must know when to create indexes to optimize performance and resource use.
Progress0 / 4 steps
1
Create the books collection with sample data
Create a MongoDB collection called books and insert exactly these three documents: { title: "Book A", genre: "Fiction", pages: 200 }, { title: "Book B", genre: "Non-Fiction", pages: 150 }, and { title: "Book C", genre: "Fiction", pages: 300 }.
MongoDB
Need a hint?

Use insertMany to add multiple documents at once.

2
Add a variable minIndexCount to control indexing
Create a variable called minIndexCount and set it to 5. This variable will decide the minimum number of documents needed before creating an index.
MongoDB
Need a hint?

Use const to declare the variable minIndexCount.

3
Write a conditional index creation logic
Write code that counts documents in books and creates an index on genre only if the count is greater than or equal to minIndexCount. Use db.books.countDocuments() and db.books.createIndex({ genre: 1 }).
MongoDB
Need a hint?

Use countDocuments() to get the number of documents, then an if statement to check if it meets minIndexCount.

4
Finalize collection without unnecessary indexes
Ensure the books collection does not have an index on genre if the document count is less than minIndexCount. Do not create the index manually.
MongoDB
Need a hint?

Do not create the index manually if the count is below the threshold.