MongoDB

MongoDB is a document-oriented NoSQL database that stores data as flexible, JSON-like documents (BSON) instead of rows in tables. Application objects map almost directly to documents, which speeds up development and suits data whose shape varies or evolves.

It's a natural fit for JavaScript/Node.js stacks and apps that need flexible schemas and horizontal scaling. The trade-off is that you design around query patterns and relationships yourself, rather than relying on a fixed relational schema and joins.

TL;DR

Quick Example

Insert a document and query it — note the nested structure stored directly:

Core Concepts

Data Modeling

The central decision is embed vs reference:

Model for how you query, not how you'd normalize in SQL. Unbounded embedded arrays (e.g. all comments inside a post) are a classic trap — they grow without limit.

Best Practices

Comparison: MongoDB vs PostgreSQL

See PostgreSQL — which also stores JSON via JSONB.

Common Mistakes

Unbounded array growth

Treating "schemaless" as "no design"

FAQ

MongoDB or a SQL database?

Choose MongoDB for flexible/evolving schemas and document-shaped data, especially in JavaScript stacks. Choose SQL (Postgres/MySQL) for highly relational data, complex joins, and strict ACID needs. Note that Postgres can also store JSON via JSONB, narrowing the gap.

Should I embed or reference related data?

Embed data that's read together and bounded in size (an order and its items). Reference data that's large, shared across documents, or unbounded (a user's posts). The deciding factor is your query and update patterns.

Is MongoDB ACID?

Single-document operations are atomic, and MongoDB has supported multi-document ACID transactions since 4.0. But you should model so that most operations touch a single document — heavy reliance on multi-document transactions often signals a relational fit.

When should I not use MongoDB?

For strongly relational data with many-to-many relationships, complex reporting/analytics, or strict financial consistency, a relational database is usually the better tool. Mongo shines when the document model matches how you read and write.

Related Topics

References