Episode 3 — NodeJS MongoDB Backend Architecture / 3.8 — Database Basics MongoDB

3.8 — Exercise Questions: Database Basics — MongoDB

Practice questions for all seven subtopics in Section 3.8. Mix of conceptual, coding, and hands-on exercises. Try each without reopening the lesson files first.

How to use this material (instructions)

  1. Read lessons in order -- README.md, then 3.8.a through 3.8.g.
  2. Answer closed-book first -- write an answer, then compare to the lesson.
  3. Code exercises -- build working Mongoose snippets for every coding question.
  4. Redo misses -- retry wrong questions after sleep (spaced repetition).
  5. Interview prep -- pair with 3.8-Interview-Questions.md.

3.8.a -- Relational vs Non-Relational Databases (Q1-Q7)

Q1. What is the fundamental difference between a relational (SQL) and a non-relational (NoSQL) database? Give 3 examples of each.

Q2. Compare SQL and MongoDB terminology: what are the MongoDB equivalents of Table, Row, Column, Primary Key, and JOIN?

Q3. Name the four main categories of NoSQL databases (document, key-value, column-family, graph). Give one example database for each.

Q4. When would you choose MongoDB over PostgreSQL? Give 3 specific project scenarios.

Q5. When would you choose PostgreSQL over MongoDB? Give 3 specific project scenarios.

Q6. What does "schema-less" mean in the context of MongoDB? Is MongoDB truly schema-less?

Q7. Explain ACID properties. Which ones does MongoDB support natively?


3.8.b -- Introduction to MongoDB (Q8-Q14)

Q8. What does MongoDB store internally -- JSON or BSON? What are two advantages of BSON over JSON?

Q9. Explain the hierarchy: database -> collection -> document -> field. Draw an analogy to a filing cabinet.

Q10. What is a MongoDB replica set? Why is it important for production?

Q11. What is a MongoDB Atlas cluster? How does it differ from a local MongoDB installation?

Q12. List at least 5 key features of MongoDB (e.g., flexible schema, horizontal scaling, etc.).

Q13. What is sharding in MongoDB and when would you need it?

Q14. What is the mongosh shell? Write the commands to: show databases, switch to a database, show collections, drop a collection.


3.8.c -- Setting Up MongoDB (Q15-Q20)

Q15. Write the steps to install MongoDB Community Edition on your operating system.

Q16. What is MongoDB Compass? List 3 things you can do with it that are difficult in the shell.

Q17. Write the connection strings for: (a) local MongoDB, (b) MongoDB Atlas cluster.

Q18. What is the difference between mongodb:// and mongodb+srv:// connection strings?

Q19. Create a free-tier Atlas cluster and connect to it from mongosh. Write the exact commands.

Q20. Hands-on: Using mongosh, create a school database, add a students collection, insert 5 documents, and query for students older than 20.


3.8.d -- MongoDB Data Types and Documents (Q21-Q30)

Q21. List at least 10 BSON data types with an example value for each.

Q22. What is an ObjectId? Describe its 12-byte structure (timestamp, random, counter).

Q23. Why does sorting by _id sort by creation time?

Q24. Write a MongoDB shell command to insert a document with: String, Number, Boolean, Date, Array, embedded object, and ObjectId reference.

Q25. Explain the difference between embedding and referencing with an example for each.

Q26. Given a user document with an embedded address object, write the query to find users in a specific city using dot notation.

Q27. Write shell commands to: $push to an array, $pull from an array, $addToSet, and $pop.

Q28. What is the maximum document size in MongoDB? What should you use for files larger than this?

Q29. List 3 field naming rules in MongoDB (e.g., cannot start with $).

Q30. Design exercise: Design a MongoDB document for an e-commerce product with: name, price (Decimal128), multiple images, category, tags, inventory tracking, and embedded recent reviews.


3.8.e -- Mongoose ODM (Q31-Q40)

Q31. What is Mongoose? How does it differ from the native MongoDB Node.js driver?

Q32. Write the code to connect to MongoDB using Mongoose with environment variables and error handling.

Q33. Define a Mongoose schema for a Product with: name (required, trimmed, 3-100 chars), price (required, min 0, Decimal128), category (enum of 5 values), inStock (Boolean, default true), tags (array of strings), and timestamps.

Q34. Explain the difference between Schema.Types.ObjectId, Schema.Types.Mixed, and Schema.Types.Decimal128.

Q35. Write 3 custom validators: (a) a phone number regex validator, (b) an async validator that checks email uniqueness, (c) a validator that ensures endDate is after startDate.

Q36. What are Mongoose virtuals? Write a virtual fullName that combines firstName and lastName, including a setter.

Q37. Write a pre('save') middleware that hashes a password using bcrypt before saving.

Q38. What is the difference between instance methods and static methods in Mongoose? Write one of each.

Q39. Explain what { timestamps: true }, { strict: true }, and { toJSON: { virtuals: true } } do.

Q40. Coding exercise: Create a complete User model file (models/User.js) with: schema, validation, virtuals (fullName), instance method (isAdmin()), static method (findByEmail()), pre-save middleware (password hashing), and timestamps.


3.8.f -- CRUD Operations with Mongoose (Q41-Q55)

Q41. What is the difference between Model.create(), new Model().save(), and Model.insertMany()? Which runs pre-save middleware?

Q42. Write the code to create a user, then find all users with role "admin" sorted by name.

Q43. What does findOne() return if no document matches? What about findById() with a non-existent ID?

Q44. Write queries using these operators: $gt, $in, $or, $regex, $exists, $elemMatch.

Q45. Explain projection. Write a query that returns only name and email, excluding _id.

Q46. Write a pagination function that accepts page and limit from query params and returns data with pagination metadata.

Q47. What is the difference between findByIdAndUpdate() and using findById() + modify + save()? When would you use each?

Q48. Why must you pass { runValidators: true } to findByIdAndUpdate()? What happens without it?

Q49. Write update operations using: $set, $inc, $push, $pull, $addToSet, $unset.

Q50. Explain the soft-delete pattern. Write the schema modifications and pre-find middleware to implement it.

Q51. What is lean() and when should you use it? What does it NOT return?

Q52. Write a complete Express error handler that catches: ValidationError, duplicate key (code 11000), and CastError.

Q53. Coding exercise: Build a complete CRUD REST API for a Book resource (title, author, isbn, year, genre, pages) with:

  • Validation on all fields
  • Pagination, sorting, and filtering on GET /books
  • lean() on read queries
  • Proper error handling
  • Soft delete

Q54. Write a dynamic query builder that accepts filter, sort, page, limit, and select from req.query and builds a Mongoose query chain.

Q55. What does countDocuments() do? Why is it better than find().length for pagination?


3.8.g -- Database Relations and Populate (Q56-Q68)

Q56. Explain the three relationship types (1:1, 1:many, many:many) with a real-world example for each.

Q57. What is the difference between embedding and referencing? Draw a comparison table with at least 5 criteria.

Q58. Write schemas for a 1:many relationship between Author and Book where each book references its author.

Q59. Write the code to create an author, create 3 books referencing that author, then find all books by that author.

Q60. What does populate() do? How many queries does it actually send to MongoDB?

Q61. Write a populate that: (a) populates a single field, (b) populates with field selection, (c) populates multiple paths.

Q62. What is nested (deep) populate? Write an example: Comment -> Post -> Author.

Q63. Explain virtual populate. Write a schema that adds a virtual posts field to an Author model.

Q64. Implement a many-to-many relationship between Student and Course using: (a) arrays of references, (b) a junction collection with enrollment date and grade.

Q65. What is the N+1 query problem? How does populate() solve it?

Q66. Compare populate() and $lookup. When would you use each?

Q67. Coding exercise: Build a blog API with Author, Post, and Comment models. Include:

  • Author has virtual posts
  • Post references Author
  • Comment references Post and Author
  • GET /posts returns posts with author name
  • GET /posts/:id returns post with author and comments
  • GET /authors/:id returns author with their published posts

Q68. Write a populate with match and options that returns only published posts sorted by date, limited to 5.


Cross-Topic Challenges (Q69-Q75)

Q69. Design a complete MongoDB schema for a task management app (users, projects, tasks, comments). Decide embedding vs referencing for each relationship and justify.

Q70. You have a users collection with 1 million documents. Write optimized queries for:

  • Find users by email (unique)
  • Find all active admins sorted by name
  • Count users registered this month
  • Paginate users (page 50, limit 20)

Q71. Explain the difference between mongoose.connect() event listeners (connected, error, disconnected) and how to handle graceful shutdown.

Q72. A junior developer writes: const user = await User.findByIdAndUpdate(id, req.body). List every problem with this line and how to fix each.

Q73. Full coding project: Build a REST API for a recipe application with:

  • User model (name, email, password with hashing)
  • Recipe model (title, ingredients array, steps array, author ref, tags, difficulty enum)
  • Comment model (text, user ref, recipe ref)
  • Full CRUD for recipes with auth
  • Populate author and comments
  • Pagination, sorting, filtering by tags/difficulty
  • Error handling

Q74. Compare Mongoose schema validation with express-validator / Zod. When should each layer run? Can they replace each other?

Q75. Write a Mongoose plugin that adds createdBy and updatedBy fields to any schema, automatically populated from the request user.


Answer Hints (Short)

QHint
Q2Table=Collection, Row=Document, Column=Field, PK=_id, JOIN=populate/$lookup
Q7MongoDB supports atomicity at document level; multi-doc transactions added in 4.0
Q8BSON; supports more types (Date, ObjectId); more efficient for parsing
Q224 bytes timestamp + 5 bytes random + 3 bytes counter = 12 bytes
Q2816 MB; use GridFS for larger files
Q31ODM that adds schemas, validation, middleware, populate on top of native driver
Q41create() and save() run pre-save middleware; insertMany() does not
Q47findByIdAndUpdate skips pre-save middleware; findById+save runs it
Q48Without it, schema validators are skipped on updates
Q51lean() returns plain JS objects; no virtuals, methods, or save()
Q60Mongoose issues a second query to the referenced collection
Q65Without populate: 1 query for list + N queries for each ref; populate batches into 2 queries
Q72No new: true, no runValidators, trusts raw req.body, no error handling

<- Back to 3.8 -- Database Basics: MongoDB (README)