Document Databases with MongoDB

Model, query, index and validate data in MongoDB, the most widely used document database.

Intermediate · about 10 hours · difficulty 3/5

Learn first: NoSQL Families and When to Use Them

MongoDB stores data as BSON documents (binary JSON) grouped into collections. It is the NoSQL database you are most likely to meet in job descriptions and startups, and many Node.js stacks pair it with the Mongoose ODM.

Modeling: embed or reference

The central design question is whether related data lives inside a document or in a separate collection:

  • Embed when data is owned by the parent and read together (an order and its line items).
  • Reference when data is shared, large or grows without bound (users and their thousands of comments).

Documents have a 16 MB limit, and unbounded arrays are a classic performance trap.

Querying

  • CRUD with find, insertOne, updateOne and operators like $set, $push, $in, $gte.
  • The aggregation pipeline ($match, $group, $lookup, $project) handles reporting and joins-when-needed.
  • Indexes work much like SQL: single-field, compound (order matters), multikey for arrays, text and TTL indexes. Use explain() to confirm queries hit an index.

Consistency and safety

Single-document writes are atomic, and multi-document transactions exist on replica sets, but a design that needs them everywhere is a hint you wanted a relational database. Use schema validation (JSON Schema rules on the collection) or an ODM so bad data does not creep in.

Pitfalls

  • Treating "no schema" as "no design", ending with ten shapes of the same entity.
  • Missing indexes, which turn every query into a collection scan.
  • Exposing the database to the internet without authentication, historically a major source of breaches.

You are ready to move on when you can model a blog with posts, comments and tags, justify each embed or reference decision, and show via explain() that your main queries use indexes.

Key concepts

  • Documents, collections and BSON
  • CRUD operations and query operators
  • Embedding vs referencing
  • Indexes and explain()
  • Aggregation pipeline
  • Schema validation
  • Mongoose ODM: Common in Node.js projects
  • Multi-document transactions

Mini project

Build a small blog API on MongoDB with embedded comments, referenced authors, a compound index for the feed query and an aggregation that returns post counts per tag.

Check yourself

When would you move comments out of the post document into their own collection?

Free resources