When to Use MongoDB: Does the Document Model Make Sense?
When to use MongoDB and when not to: concrete criteria for choosing between the document model and relational tables.
You reached for MongoDB because someone on the team said "rigid schemas slow the product down," modeled everything as nested documents, and three months later you're stacking $lookup on top of $lookup to stitch orders, customers and payments back together. The feeling is familiar: you reinvented the JOIN with less help from the database, and transactions across collections, which do exist, turned out more expensive and more limited than you expected. The problem is rarely MongoDB. It's having picked the document model for data that is, at its core, relational.
The short answer: use MongoDB when the entity has a clear boundary (it's read and written as one block, by a key) and its shape varies between records. Prefer PostgreSQL when the data is a web of relationships queried from several angles, when there are cross-cutting reports, and when business rules depend on transactions across several entities. The rest of this post details those criteria, with examples I ran on MongoDB 8.0 and PostgreSQL 17.
What a document actually is
In the relational model you split an entity across several normalized tables and reassemble it with JOINs at read time. In MongoDB you store the entity the way it's consumed: an order with its line items and a customer snapshot, all in a single BSON document.
{
"_id": "ord_8821",
"customer": { "id": "cus_42", "name": "Ana Lima" },
"items": [
{ "sku": "KEY-01", "qty": 2, "price": 149.9 },
{ "sku": "MOU-03", "qty": 1, "price": 89.0 }
],
"total": 388.8,
"status": "paid"
}
The rule MongoDB's own documentation keeps repeating is: data that is accessed together is stored together. If your screen shows the whole order at once, reading that document is a single query by _id, no JOIN. That's where the document model shines, and that's where most people misjudge the technology: they judge the database by the case where the data doesn't have that shape.
MongoDB vs PostgreSQL in 5 criteria
| Criterion | MongoDB | PostgreSQL |
|---|---|---|
| Data shape | Self-contained aggregate, read by key | Independent entities linked by relationships |
| JOINs | $lookup in the aggregation pipeline; works, but the model asks you to avoid it |
JOIN is the core use case, with a mature planner |
| Transactions | Multi-document since 4.0 (replica set) and 4.2 (sharded); 60 s default limit | ACID across any tables, no duration limit by default |
| Schema | Flexible by default; optional validation with $jsonSchema |
Strict by default; flexible where you want with JSONB |
| Horizontal scale | Native sharding by key | Native read replicas; write sharding depends on an extension or architecture |
The last row carries the most weight in the conversation and matters least for most projects: a single well-configured PostgreSQL server handles far more than most products will ever need. If the decision is between PostgreSQL and another relational database, the PostgreSQL vs MySQL comparison covers the other half of the choice.
When to use MongoDB
Documents win when the shape of the data and the access pattern are on your side:
- The entity is read and written as one block. Shopping cart, user profile, account settings, a post with embedded comments. You almost never want "just the items" without the order.
- The schema varies between records. A product catalog where a TV has a screen size and a t-shirt has a size label. In a relational store that becomes nullable columns or a generic attribute table (the dreaded EAV); in a document, each product carries only the fields it has.
- The data evolves fast and several shapes coexist. The win here isn't dodging the cost of
ALTER TABLE(more on that below), it's having old and new documents side by side without a coordinated migration for every change. - You need to scale writes horizontally. Native sharding distributes documents by key across shards. It's a more direct path than partitioning a relational database by hand.
- The data arrives semi-structured. Events, webhook payloads, telemetry: high-volume things that show up in irregular shapes.
Notice the pattern: every one of these has a clear aggregation boundary. The document is the natural unit of reading and writing.
"Flexible schema" doesn't mean "no schema"
Since version 3.6, MongoDB validates documents with $jsonSchema at write time. Flexible is the default, not the only option:
db.createCollection("orders", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["customer", "items", "total", "status"],
properties: {
items: { bsonType: "array", minItems: 1 },
total: { bsonType: ["double", "int", "decimal"], minimum: 0 },
status: { enum: ["open", "paid", "cancelled"] }
}
}
}
})
db.orders.insertOne({ customer: { id: "cus_42" }, items: [], total: 0, status: "paid" })
// MongoServerError: Document failed validation
I ran it on MongoDB 8.0: the order with no items is rejected. If the argument for MongoDB is "we don't want a schema," know that at some point you'll want one, and you can have it.
When not to use MongoDB (and PostgreSQL is better)
This is where the original mistake lives. The document model charges a steep price when the data is essentially a many-to-many web queried from different angles:
- Many JOINs across independent entities. If nearly every query needs a
$lookuplinking separate collections, the data is relational.$lookupworks, but you're using the database on its least natural terrain. - Transactions across several entities are the heart of the rule. MongoDB has had multi-document ACID transactions since 4.0 on replica sets and since 4.2 on sharded clusters. They work: I ran the transfer between two accounts below on a single-node replica set and the commit was atomic. But the documentation is explicit that a distributed transaction costs more than single-document writes and is no replacement for good schema design. And there are limits: by default a transaction must finish in under a minute (
transactionLifetimeLimitSeconds = 60), and on a standalonemongodit isn't available at all. - The same information is queried along several axes. A report crossing sales by region, by rep and by product benefits from normalized tables and SQL. Duplicating that across documents becomes a consistency nightmare.
- Auditing and reporting assume SQL. BI, reconciliation and audit tools usually speak SQL out of the box. No regulation requires a particular kind of database, but it's real friction when financial data lives in a document store.
const s = db.getMongo().startSession()
const accounts = s.getDatabase("shop").accounts
s.startTransaction()
try {
accounts.updateOne({ _id: "A", balance: { $gte: 300 } }, { $inc: { balance: -300 } })
accounts.updateOne({ _id: "B" }, { $inc: { balance: 300 } })
s.commitTransaction()
} catch (e) {
s.abortTransaction()
throw e
}
There's also a silent cost: to avoid JOINs you duplicate data (the customer snapshot in every order, for instance). That uses more disk and creates the problem of keeping copies in sync when the original changes. If you caught yourself writing routines to propagate a customer's name change across 40,000 documents, the model is wrong for that data. Sometimes the snapshot is the right behavior (the order should keep the address from the time of purchase), and then the duplication is a feature; the question is whether the copy should change when the original does.
The ALTER TABLE argument has aged
A classic argument for documents is that "adding a field doesn't require an ALTER TABLE across millions of rows." In PostgreSQL, that stopped being true in version 11: ADD COLUMN with a non-volatile default became a metadata-only change, with no table rewrite. I tested it on PostgreSQL 17 with 1 million rows:
ALTER TABLE products ADD COLUMN active boolean NOT NULL DEFAULT true;
-- Time: 0.938 ms (the table file, pg_relation_filenode, did not change)
MongoDB's real win here isn't the cost of ALTER. It's living with different shapes without a coordinated migration, which is great early in a product and becomes debt when nobody knows which shapes exist in the collection anymore.
Embed or reference: the decision that defines everything
Inside MongoDB itself lives the choice that most separates healthy projects from painful ones: embedding (nesting) versus referencing (by id, foreign-key style).
Embed when the relationship is containment and the child can't live alone: line items of an order, comments on a low-volume post. Reference when the sub-object is large, grows without bound or is shared by several parents. The choice of identifier matters too; the trade-offs in the post on natural vs surrogate primary keys apply just as much to _id.
// Embedding: items live inside the order
db.orders.findOne({ _id: "ord_8821" }) // everything in 1 read
// Referencing: comments in their own collection
db.comments.find({ post_id: "post_42" }).limit(20)
// And when you need to join, $lookup:
db.orders.aggregate([
{ $lookup: { from: "customers", localField: "customer.id", foreignField: "_id", as: "cus" } }
])
MongoDB documents have a 16 MB limit (the BSON document size limit). An ever-growing list, like the activity feed of a user active for years, can't be embedded: it will blow past the document size. In practice, that limit is your wrong-modeling detector.
The choice isn't binary
Mature teams don't pick "MongoDB or PostgreSQL" for the whole system. They pick per context: product catalog in documents, financial ledger in relational, sessions and cache in Redis (the post on Redis use cases covers that piece). For the broader difference between database families, the relational vs NoSQL comparison treats the decision at a more architectural level. And if the project is small enough not to need a database server at all, the post on when to use SQLite is the right read.
PostgreSQL, by the way, has JSONB, which stores documents with GIN indexes and containment operators:
CREATE INDEX products_attrs_gin ON products USING gin (attrs jsonb_path_ops);
SELECT name, price FROM products WHERE attrs @> '{"size": "M"}';
For a small slice of flexible data (the catalog's variable attributes) inside a mostly relational system, that solves it without bringing in a second database to operate, back up and monitor.
Frequently asked questions
When should you use MongoDB instead of a relational database?
When the entity is read and written as one cohesive block, the schema varies between records, several shapes need to coexist, or you need horizontal write scaling. If your access pattern is "fetch the whole document by a key," the document model is direct and fast.
When should you not use MongoDB?
When the data is a many-to-many web queried from several angles, when business rules depend on transactions across many entities, or when reporting and auditing cross everything with everything. If you're writing $lookup in nearly every query, the data is relational.
Does MongoDB support ACID transactions?
Yes. Multi-document transactions exist since version 4.0 on replica sets and since 4.2 on sharded clusters. The documentation itself warns that they cost more than single-document writes and don't replace good schema design; by default, a transaction expires if it runs longer than 60 seconds.
Can you use MongoDB and PostgreSQL in the same project?
Yes, and it's common. Use each database where it's strong: documents for self-contained, variable-schema entities; relational for the transactional core and cross-cutting reports. If the flexible part is small, JSONB in PostgreSQL itself is usually enough and saves you one more database to run.
Choose by the shape of the data, not the trend
The document model isn't "the future" or a "passing fad": it's a choice about the shape of your data. Ask whether the entity has a clear aggregation boundary, whether it's read as a block, and whether the 16 MB limit leaves room. If so, MongoDB will serve you well, with schema validation where you need it. If you find yourself rebuilding JOINs with $lookup, syncing copies by hand or fighting transactions across collections, that data wanted to be a table all along. When I inspect a real document before deciding (a mongoexport dump or an API response), I paste it into the JSON Formatter to see the whole tree and what is actually read together.
- 01 CPU Cores vs. Threads: What Actually Changes in Practice Understand the difference between CPU cores and threads and what actually changes for performance, multitasking, gaming, and development.
- 02 MIT, Apache, and GPL Licenses: Practical Differences for Developers MIT, Apache 2.0, and GPL are not the same thing. Understand permissive vs copyleft, patent protection, and compatibility before shipping code to production.