10. NoSQL in Postgres: JSONB Mastery
The Best of Both Worlds
You don't need MongoDB to store JSON. Postgres handles JSON better than most NoSQL databases. With JSONB (Binary JSON), you get the flexibility of a document store with the power and safety of a relational database.
JSON vs JSONB: Why the B matters
Stored as exact text. Slow to process because it must be parsed every time. Best for simple storage/audit logs.
Stored in binary format. Fast to query, supports GIN Indexes, and automatically removes duplicate keys and whitespace.
Querying inside JSONB
Postgres has specialized operators for reaching into your JSON documents.
- ->: Returns a JSON object/array.
- ->>: Returns the value as TEXT. (Most common for
WHEREclauses). - @>: The
Containsoperator. Checks if a JSON document contains another.
-- Find all users with the 'admin' role in their metadata JSON SELECT * FROM users WHERE metadata @> '{"roles": ["admin"]}';
Performance: GIN Indexes on JSONB
The secret to JSONB speed is the GIN (Generalized Inverted Index). It creates a map of every key and value inside the JSON document, allowing for sub-millisecond searches across millions of documents.
CREATE INDEX idx_user_meta_gin ON users USING GIN (metadata);
Knowledge Check
Ready to test your understanding of 10. NoSQL in Postgres: JSONB Mastery?