Nov 18, 20266 min read

MongoDB vs Postgres for Backend Apps

A head-to-head on data modelling, transactions, JSON, scaling, licensing and managed hosting for teams choosing a primary database in 2026, with the same order model built in both.

Illustration for MongoDB vs Postgres for Backend Apps

MongoDB and Postgres are the two most common answers to "which database should the backend use", and both are capable of running most applications. MongoDB stores JSON-like documents and lets each one have its own shape; Postgres stores rows in tables with a schema and has grown a strong JSON type over the last decade. The choice shapes how you write queries, migrations and transactions for years.

The difference often shows up in the second year, when reports need joins across collections, when a document grows past what one record should hold, or when a migration needs to backfill a field in millions of rows. This guide compares the two on the points that decide that, with the same order model built in both.

MongoDB vs Postgres at a glance

PostgresMongoDB
Data modelTables, rows, foreign keys, plus jsonb columnsCollections of BSON documents
SchemaDeclared, changed with migrationsFlexible, optional JSON Schema validation
JoinsNative, planner-optimized$lookup in aggregation pipelines
TransactionsACID, any number of rows and tablesSingle-document atomic; multi-document ACID since 4.0
Horizontal write scalingRead replicas built in; sharding via extensions such as CitusBuilt-in sharding
LicensePostgreSQL License (permissive)SSPL for the server
Managed on AWSRDS, AuroraAtlas on AWS, or DocumentDB (compatible API)
Managed on GCPCloud SQL, AlloyDBAtlas on GCP

Data modelling

In the classic order-with-line-items example, MongoDB embeds the items in the order document, so reading an order is one lookup and writing it is one atomic operation:

db.orders.insertOne({ _id: "ord_123", customerId: "cus_42", status: "pending", items: [ { sku: "TSHIRT-M", qty: 2, priceCents: 1500 }, { sku: "MUG", qty: 1, priceCents: 900 } ], createdAt: new Date() });

Postgres splits it into two tables with a foreign key, and the database rejects an item for an order that does not exist:

CREATE TABLE orders ( id TEXT PRIMARY KEY, customer_id TEXT NOT NULL, status TEXT NOT NULL CHECK (status IN ('pending', 'paid', 'cancelled')), created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE TABLE order_items ( order_id TEXT NOT NULL REFERENCES orders (id) ON DELETE CASCADE, sku TEXT NOT NULL, qty INT NOT NULL CHECK (qty > 0), price_cents BIGINT NOT NULL CHECK (price_cents >= 0), PRIMARY KEY (order_id, sku) );

The embedded model wins when the order is always read whole. The relational model wins when you need "revenue by SKU last month" or "customers who bought a mug twice", which in MongoDB means an aggregation pipeline with $unwind and $group over every order, and in Postgres a GROUP BY on an indexed table. MongoDB also caps documents at 16 MB, which matters for anything that grows without bound, like an activity log embedded in a user.

JSON in Postgres

Postgres's jsonb type covers many of the cases that push teams toward MongoDB: per-tenant custom fields, webhook payloads, product attributes that differ by category. A GIN index makes containment queries fast:

ALTER TABLE products ADD COLUMN attributes JSONB NOT NULL DEFAULT '{}'; CREATE INDEX products_attributes_gin ON products USING GIN (attributes jsonb_path_ops); SELECT id, name FROM products WHERE attributes @> '{"color": "black", "size": "M"}';

What you give up compared with MongoDB is update ergonomics: jsonb_set and the || operator work, but MongoDB's $inc, $push and array filters on nested paths are more natural for heavy in-place document edits.

Transactions and consistency

MongoDB has had multi-document transactions since 4.0, with limits on duration and recommended size, and its documentation still steers designs toward single-document atomicity. Postgres transactions span any number of rows and tables with no special mode, and constraints such as CHECK, UNIQUE and foreign keys are enforced at commit. For money, inventory and anything with invariants across records, that is the deciding point for many teams.

Scaling

MongoDB shards collections across replica sets by a shard key, built into the server, which suits very high write volumes on data that partitions cleanly by tenant or device. Postgres scales vertically to large instances, adds read replicas for read traffic, and shards with extensions like Citus when it has to. Most applications never outgrow a well-sized Postgres primary with replicas, and picking a database for sharding you do not need adds operational cost from day one.

Licensing and hosting

MongoDB moved its server to the Server Side Public License in 2018, which is why AWS offers DocumentDB, a MongoDB-compatible service on its own engine, rather than MongoDB itself; Atlas is MongoDB's managed service on all three clouds. Postgres uses a permissive license, and every cloud runs it natively: RDS and Aurora on AWS, Cloud SQL and AlloyDB on GCP.

Best fit: Postgres for business applications with relationships, reporting and invariants, using jsonb for flexible parts. MongoDB for document-shaped data read as a unit, rapidly varying per-record structure, and write volumes that need built-in sharding.

How do you use Postgres with Encore?

Encore

Encore is a backend framework with built-in infrastructure, and its database primitive is Postgres. You declare a database and write migrations; encore run starts Postgres locally, and on deploy Encore provisions RDS or Aurora on AWS, or Cloud SQL on GCP, in your own account. The order model above becomes a migration and a typed endpoint:

package orders import ( "context" "encore.dev/storage/sqldb" ) var db = sqldb.NewDatabase("orders", sqldb.DatabaseConfig{Migrations: "./migrations"}) type Item struct { SKU string `json:"sku"` Qty int `json:"qty"` } type CreateParams struct { ID string `json:"id"` CustomerID string `json:"customer_id"` Items []Item `json:"items"` } //encore:api public method=POST path=/orders func Create(ctx context.Context, p *CreateParams) error { tx, err := db.Begin(ctx) if err != nil { return err } defer tx.Rollback() if _, err := tx.Exec(ctx, ` INSERT INTO orders (id, customer_id, status) VALUES ($1, $2, 'pending')`, p.ID, p.CustomerID); err != nil { return err } for _, it := range p.Items { var price int64 if err := tx.QueryRow(ctx, ` SELECT price_cents FROM products WHERE sku = $1`, it.SKU).Scan(&price); err != nil { return err } if _, err := tx.Exec(ctx, ` INSERT INTO order_items (order_id, sku, qty, price_cents) VALUES ($1, $2, $3, $4)`, p.ID, it.SKU, it.Qty, price); err != nil { return err } } return tx.Commit() }

The handler loads each SKU's price from the catalog inside the transaction, so a caller cannot submit its own price. The order and its items commit together, and the CHECK constraints reject a zero quantity no matter which code path inserts it. Encore does not provision MongoDB; if part of your system needs it, Atlas or DocumentDB runs alongside, with its connection string stored as an Encore secret. Encore provisions an IAM role for the service, or a service account on GCP.

For coding agents, Postgres with migrations in the repository is a clear contract: a schema change is a reviewed SQL file that runs against local Postgres on encore run and against a fresh database in preview environments before production.

Best fit: teams that choose Postgres and want it running locally and in their own AWS or GCP account from the same code, with migrations applied on deploy.

How to choose

Default to Postgres for a new backend, and use jsonb columns for the flexible parts. Choose MongoDB when your core data is genuinely document-shaped and read whole, when per-record structure varies a lot, or when you know you will need built-in sharding. If you build on Encore, Postgres is provisioned and migrated for you in your cloud account, and MongoDB is an external service you connect with a secret.

Frequently asked questions

Is MongoDB or Postgres better for a new backend?

For most business applications, Postgres is the safer default: relational integrity, mature SQL, transactions and jsonb for the parts that are document-shaped. MongoDB fits when data is naturally nested documents read and written as a unit, the schema changes often per record, and you expect to shard writes horizontally.

Can Postgres replace MongoDB for JSON data?

Often, yes. Postgres jsonb stores binary JSON, supports containment and path queries, and can be indexed with GIN or expression indexes. You lose MongoDB's document-level update operators and its built-in sharding, but you can join JSON with relational data and enforce constraints in the same transaction.

Does MongoDB support transactions?

Yes. MongoDB has supported multi-document ACID transactions on replica sets since 4.0 and on sharded clusters since 4.2. Single-document writes are atomic without a transaction, which is why MongoDB schemas often embed related data in one document.

How do I use Postgres with Encore?

Declare a database with sqldb.NewDatabase in Go or new SQLDatabase in TypeScript and add SQL migrations. encore run starts Postgres locally, and on deploy Encore provisions RDS or Cloud SQL in your own AWS or GCP account with the database created and migrations applied.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders