PostgreSQL JSONB as an Alternative to MongoDB
Using Postgres JSONB with GIN indexing for flexible document data alongside relational tables and transactions, and when MongoDB can still make sense.
· 2 min read · Erik Kubica
The 2012 Document Promise
Around 2012, MongoDB caught a lot of developer attention with an appealing premise: schemas are rigid, so store your application data as raw JSON documents and ship features faster.
Many startups adopted it. I watched some teams build whole platforms on MongoDB and then spend years rebuilding relations, foreign key integrity, and transactions in their application code.
Some of them added Mongoose to enforce schemas on top of the schemaless database.
Meanwhile, PostgreSQL added JSONB in version 9.4 and later improved it with expression indexing and jsonb_path_ops.
Once Postgres had indexed, binary-encoded JSON with full ACID transactions, it covered much of what I had been using MongoDB for on the projects I work on.
For me, Postgres covered most document needs by adding JSON storage to relational tables.
The Operational Side
Running a dedicated MongoDB cluster in production comes with some chores:
- The WiredTiger storage engine allocates 50% of available server RAM for its cache by default.
- You need a minimum 3-node replica set for high availability, which roughly triples server costs.
- On AWS or Atlas, a basic 3-node replica set with 8 GB of RAM costs roughly 160 $ to 220 $ per month.
- You now operate two database engines with separate backup scripts, monitoring alerts, and connection pools.
On a single 4-core production server (4 vCPU, 8 GB RAM), PostgreSQL can handle relational user accounts and billing data, while storing polymorphic event payloads in a JSONB column on the same table.
GIN Indexes: Querying 1.2 Million Documents in 0.8ms
Here is what JSONB looks like in practice:
-- Create an event tracking table with structured + unstructured fields
CREATE TABLE audit_events (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
tenant_id text NOT NULL,
action text NOT NULL,
metadata jsonb NOT NULL,
created_at timestamptz DEFAULT now()
);
-- Build a specialized Generalized Inverted Index (GIN)
CREATE INDEX idx_audit_metadata_path
ON audit_events USING gin (metadata jsonb_path_ops);
Using jsonb_path_ops creates an index optimized for JSON containment queries with the @> operator.
Here is how you query for nested attributes:
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, tenant_id, metadata->>'device_os' AS os
FROM audit_events
WHERE metadata @> '{"billing": {"plan": "enterprise"}, "status": "active"}'
LIMIT 50;
And the query planner output on a table containing 1.2 million rows:
Limit (cost=12.45..182.10 rows=50 width=42) (actual time=0.482..0.814 rows=50 loops=1)
-> Bitmap Heap Scan on audit_events (actual time=0.480..0.805 rows=50 loops=1)
Recheck Cond: (metadata @> '{"billing": {"plan": "enterprise"}, "status": "active"}'::jsonb)
-> Bitmap Index Scan on idx_audit_metadata_path (actual time=0.412..0.412 rows=1420 loops=1)
Buffers: shared hit=42
Planning Time: 0.145 ms
Execution Time: 0.840 ms
About 0.8 milliseconds to search nested keys across 1.2 million JSON documents on that setup. You can also join those documents against your users or invoices tables in the same SQL query, with transactional safety.
One Database Instead of Two
For the projects where I tried this, one database was easier to run than two.
With PostgreSQL JSONB, you can put strict relational constraints on data that needs them (financial ledgers, user authentication, inventory) and flexible JSON on data that changes shape (audit logs, third-party webhook payloads, metadata attributes).
That gave us schema flexibility where we wanted it and relational integrity where we needed it, and on one project it let us skip about 150 $ a month of extra NoSQL infrastructure. MongoDB can still be the right choice if your data is document-shaped throughout, you need its sharding model, or your team already knows it well.