0
0
MongoDBquery~30 mins

Anti-patterns to avoid in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
Avoiding Common MongoDB Anti-patterns
📖 Scenario: You are building a simple online bookstore database using MongoDB. You want to store information about books and their authors efficiently and correctly.
🎯 Goal: Learn how to set up MongoDB collections properly by avoiding common anti-patterns such as embedding too much data, using inconsistent data types, and not indexing properly.
📋 What You'll Learn
Create a books collection with specific fields
Create an authors collection separately
Use references between collections instead of embedding all data
Add an index on the title field in books
Avoid storing arrays with inconsistent data types
💡 Why This Matters
🌍 Real World
This project models a real online bookstore database where authors and books are stored separately to keep data organized and efficient.
💼 Career
Understanding how to avoid MongoDB anti-patterns is essential for database developers and administrators to build scalable and maintainable applications.
Progress0 / 4 steps
1
Create the authors collection with sample data
Create a MongoDB collection called authors and insert exactly two documents with these fields: _id as ObjectId, name as string, and birth_year as number. Use these exact values: first author with name "Jane Austen" and birth_year 1775, second author with name "Mark Twain" and birth_year 1835.
MongoDB
Need a hint?

Use insertMany to add multiple documents to the authors collection.

2
Create the books collection with references to authors
Create a MongoDB collection called books and insert exactly two documents with these fields: title as string, author_id as ObjectId referencing the _id of the author in the authors collection, and year_published as number. Use these exact values: first book titled "Pride and Prejudice" by Jane Austen published in 1813, second book titled "Adventures of Huckleberry Finn" by Mark Twain published in 1884.
MongoDB
Need a hint?

Use findOne to get the _id of each author and reference it in the books documents.

3
Add an index on the title field in books
Create an index on the title field in the books collection to improve search performance. Use the exact command to create this index.
MongoDB
Need a hint?

Use createIndex on the books collection specifying the title field with ascending order.

4
Avoid inconsistent data types in arrays
Modify the books collection to add a new field called genres which is an array of strings. Insert exactly these genres for each book: for "Pride and Prejudice" use ["Romance", "Classic"], for "Adventures of Huckleberry Finn" use ["Adventure", "Classic"]. Ensure all array elements are strings to avoid inconsistent data types.
MongoDB
Need a hint?

Add the genres field as an array of strings inside each book document.