How to Migrate MongoDB to PostgreSQL (3 Methods)
Moving from MongoDB to PostgreSQL is mostly a data-modelling job, not a copy job. Documents have to become rows, embedded arrays have to go somewhere, and every collection that grew a few odd fields over the years has to fit a schema. This guide shows three ways to do it, from a one-off export to live replication, with SQL you can run. (Moving to MySQL instead? See MongoDB to MySQL.)
| Method | Best for | Downtime | Effort |
|---|---|---|---|
| 1. mongoexport → JSONB staging → SQL | One-time moves, up to a few million documents | Write freeze during export + load | Low |
| 2. Python script (pymongo + psycopg) | Large or filtered collections, resumable runs | Write freeze, or re-run deltas | Medium |
| 3. Live CDC with NoSQLSync | Production apps that can't stop writing | Near zero (switch when in sync) | Low |
Before you start: decide the shape of each table
PostgreSQL gives you a middle path MongoDB-to-MySQL moves don't have: JSONB (see PostgreSQL JSON types and our schema mapping guide). You don't have to normalise everything on day one.
- Fields you filter, join or sort on → real typed columns (
email text,created_at timestamptz). - Embedded objects you read whole (an address, settings) → a
jsonbcolumn. Add a GIN index if you query inside it. - Arrays you query item by item (order lines, tags) → a child table with a foreign key.
- Fields with mixed types across documents → keep them in
jsonbuntil you clean them.
For _id, the simplest choice is to keep the ObjectId as its 24-character hex string in a varchar(24) primary key. Every reference stored in other collections then still matches. If you want integer keys, add a bigint generated always as identity column and keep mongo_id as a unique column during the move.
Method 1: mongoexport into a JSONB staging table
The trick that top guides skip: don't export to CSV. CSV flattens nested data and mangles arrays. Export JSON, load each document into one jsonb column, then reshape it with SQL.
Step 1: export each collection (one document per line, relaxed Extended JSON is the default; see the mongoexport examples):
In this format an ObjectId looks like {"$oid": "6650f1c2..."} and most dates look like {"$date": "2024-05-01T10:00:00Z"}.
Step 2: load the raw documents into PostgreSQL. The QUOTE/DELIMITER options stop COPY from treating backslashes and commas inside the JSON as special characters:
Step 3: create typed tables and fill them from the staging rows.
The CASE handles dates before 1970 or after 9999, which relaxed JSON writes as milliseconds ($numberLong) instead of a string. COALESCE on _id covers collections that use string IDs.
Turning arrays into child tables
An array of plain values (tags) becomes one row per value:
An array of objects (order lines) keeps its order with WITH ORDINALITY. Prices stored as Decimal128 arrive as {"$numberDecimal": "19.99"}, so read both forms:
Once the counts match (see Validation), drop the staging tables.
Method 2: a Python script for big or resumable runs
For collections too large to export to one file, stream documents straight into the same staging table with pymongo and psycopg 3, then reuse the SQL above:
To resume after a failure, record the last _id written and restart with src.find({"_id": {"$gt": last_id}}). The same pattern copies only new documents if your IDs are ObjectIds (they grow over time), but it will miss updates and deletes. For those you need change data capture.
Method 3: live replication with NoSQLSync (no write freeze)
Methods 1 and 2 need you to stop writes, or accept that the copy goes stale. If your app can't pause, NoSQLSynccopies the existing data and then keeps PostgreSQL in sync by reading MongoDB's oplog:
- Paste your MongoDB connection string. NoSQLSync samples each collection and infers the schema, including nested fields.
- Review the mapping: ObjectId →
VARCHAR(24), dates →TIMESTAMPTZ, embedded documents →JSONBby default, or flatten chosen fields into their own columns. - Start the bulk copy and turn on CDC. Inserts, updates and deletes keep flowing while MongoDB stays your live database. NoSQLSync never writes to the source.
- Point your app at PostgreSQL when you're ready, and stop the sync.
CDC reads the oplog, so the source must run as a replica set (MongoDB Atlas clusters always do). The same flow works for Supabase or Neon (both PostgreSQL). Start a migration or see pricing.
Useful PostgreSQL tricks after the move
- Query inside JSONB fast:
CREATE INDEX ON users USING gin (address jsonb_path_ops);thenWHERE address @> '{"country": "BD"}'. - Get the creation time hidden in an ObjectId (its first 4 bytes are a Unix timestamp):
to_timestamp(('x' || lpad(substr(id, 1, 8), 16, '0'))::bit(64)::bigint). - Rename camelCase fields to snake_case in the
SELECTlist now, so nobody has to quote"createdAt"for years.
Validate before you cut over
Run these for every collection and child table:
Then spot-check 50–100 random IDs field by field. Mismatches usually come from a field whose type changed over time (a number stored as a string in older documents).
Cutover checklist
- Freeze writes (Methods 1–2) or wait until CDC lag is zero (Method 3).
- Re-run the counts above.
- Switch the app's connection string and deploy the PostgreSQL query layer.
- Keep MongoDB read-only for a week so you can roll back by switching the connection string back. (Infisical's MongoDB-to-PostgreSQL migration write-up used a short read-only window.)
Moving the other way, from PostgreSQL to MongoDB? NoSQLSync only moves data from NoSQL databases into SQL, so this guide won't help with that direction.
Frequently asked questions
Can PostgreSQL store MongoDB documents as they are?
Yes. A jsonb column holds any document, and GIN indexes make queries inside it fast. Most teams keep JSONB for rarely-queried nested data and move hot fields into typed columns.
What should I do with MongoDB ObjectIds in PostgreSQL?
Keep them as 24-character strings in a varchar(24) primary key so cross-collection references still match. Add an integer identity column later if you want one.
How do I migrate embedded arrays?
Put arrays you query item by item into a child table using jsonb_array_elements (with WITH ORDINALITY to keep order). Leave small arrays you only read whole in JSONB.
Can I migrate MongoDB to PostgreSQL without downtime?
Only with change data capture: copy the existing data, stream ongoing changes from the oplog until both sides match, then switch. Export-and-load methods need a write freeze.
Does NoSQLSync migrate PostgreSQL to MongoDB?
No. NoSQLSync moves data from NoSQL databases into SQL databases only.