DEV Community

Cover image for MongoDB to ClickHouse CDC Tutorial: From a Replica Set to One CREATE DATABASE
Shubham Baldava
Shubham Baldava

Posted on

MongoDB to ClickHouse CDC Tutorial: From a Replica Set to One CREATE DATABASE

Analytics on a MongoDB app usually starts inside MongoDB, as an aggregation pipeline that groups orders by status. It works until the collections grow and those aggregations compete with the writes the application depends on. That is when MongoDB to ClickHouse comes up, because ClickHouse is made for the scans MongoDB is not.

The hard part is keeping the two in step. Documents are rewritten in place, so an exported file never shows an update as a change.

The common ways to move the data:

  • ClickPipes for MongoDB. Change data capture (CDC) through change streams, run by ClickHouse Cloud, into ReplacingMergeTree tables with the documents kept as JSON. It exists on ClickHouse Cloud only, is billed per ClickPipe, and leaves ClickHouse as the only reader.
  • The MongoDB table engine. No copy at all. ClickHouse reads the current document on every query, so the load you wanted to move stays on MongoDB.
  • Debezium, Kafka and the ClickHouse Kafka engine. Changes land within seconds. You run Kafka, Kafka Connect and Debezium, add a materialized view per collection, and write the merge logic yourself.
  • Managed extract, load, transform (ELT) services such as Fivetran, Estuary or Airbyte Cloud. Nothing to operate, with freshness in minutes depending on the plan. Pricing is per row, per GB or per connector, for a second copy you pay to move and store.

This tutorial builds a fifth one. OLake Go, an open source (Apache 2.0) replication tool, reads the change stream and commits every collection as an Apache Iceberg table into Apache Polaris, an open source Iceberg REST (Representational State Transfer) catalog you run next to your own bucket. ClickHouse then attaches the whole catalog with one CREATE DATABASE statement, and DuckDB and Trino read the same files.

I ran all of it on 2026-10-29: MongoDB 7 as a single-node replica set, OLake Go v1.1.0, Polaris 1.8.0 on MinIO and ClickHouse 26.8.36, the long-term support (LTS) release. The first sync copied 48 documents in 15 seconds and the change sync took 8 seconds. Every figure below is from that run.

The MongoDB to ClickHouse pipeline you will build

  • Source: a MongoDB database called shop with two collections, customers and orders.
  • Catalog and storage: Polaris and MinIO in Docker, with the Parquet files in the bucket.
  • Pipeline: OLake UI from its Docker Compose install, with one job that copies both collections and then follows the change stream.
  • Readers: ClickHouse through the DataLakeCatalog engine, then DuckDB and Trino.

You need: Docker, MongoDB 4.0 or later running as a replica set (self-hosted or Atlas), ClickHouse 26.1 or later (the release where DataLakeCatalog reads REST catalogs), and about 40 minutes.

Step 1: Replica set, user and two collections

MongoDB only produces change streams in replica set mode, because they are read from the oplog. One node counts. If yours is standalone, restart mongod with --replSet rs0, then open mongosh on it:

// 1. Turn a single node into a replica set (skip this on Atlas)
rs.initiate({ _id: "rs0", members: [{ _id: 0, host: "<host>:27017" }] })

// 2. The user OLake Go logs in as
use admin
db.createUser({
  user: "olake", pwd: "<password>",
  roles: [{ role: "read", db: "shop" }, { role: "clusterMonitor", db: "admin" }]
})

// 3. The oplog size in bytes
use local
db.oplog.rs.stats().maxSize
Enter fullscreen mode Exit fullscreen mode

read covers the first copy of the collections. The change stream needs oplog access, and that comes from clusterMonitor (or readAnyDatabase) in admin.

Confirm both:

rs.status().members.map(m => m.stateStr)      // one PRIMARY
db.getSiblingDB("admin").getUsers().users.map(u => u.user)
Enter fullscreen mode Exit fullscreen mode

Next, the data. This script rebuilds the collections from my run: 8 customers with integer _id values and 40 orders whose amount is a NumberDecimal.

use shop
const now = new Date();
const people = [
  ['Aarav Mehta', 'aarav', 'Mumbai', 'gold'],    ['Priya Sharma', 'priya', 'Bengaluru', 'silver'],
  ['Liam Carter', 'liam', 'Austin', 'bronze'],   ['Sofia Rossi', 'sofia', 'Milan', 'gold'],
  ['Kenji Tanaka', 'kenji', 'Tokyo', 'silver'],  ['Emma Schulz', 'emma', 'Berlin', 'bronze'],
  ['Noah Kim', 'noah', 'Seoul', 'gold'],         ['Zara Ali', 'zara', 'Dubai', 'silver']
];
db.customers.insertMany(people.map((p, i) => ({
  _id: i + 1, name: p[0], email: p[1] + '@example.com', city: p[2], tier: p[3],
  created_at: now, updated_at: now
})));

const products = ['Laptop', 'Headphones', 'Monitor', 'Keyboard', 'Mouse', 'Webcam'];
const statuses = ['placed', 'shipped', 'delivered'];
const orders = [];
for (let n = 1; n <= 40; n++) {
  orders.push({
    _id: n, customer_id: 1 + (n % 8), product: products[n % 6],
    amount: NumberDecimal(((2000 + (n * 7919) % 120000) / 100).toFixed(2)),
    status: statuses[n % 3], created_at: now, updated_at: now
  });
}
db.orders.insertMany(orders);
Enter fullscreen mode Exit fullscreen mode

Two notes before you go on:

  • Atlas. The replica set and the oplog already exist. Create the user under Database Access with read on your database plus clusterMonitor, and allow OLake Go's IP under Network Access.
  • The oplog is the replay window. Atlas and most self-hosted installs keep 24 hours or less by default. OLake Go resumes from a token it saves after each sync, and once the oplog has rolled past that token the next sync has to begin with a fresh snapshot.

Step 2: Run Polaris and MinIO, then create the catalog

Three things have to exist before anything can be written: a Polaris server, a catalog inside it that points at a bucket, and a principal (a client id plus a secret) allowed to manage that catalog. Save this as docker-compose.yml and run docker compose up -d:

services:
  minio:
    image: minio/minio
    hostname: lake-minio
    command: server /data --console-address ":9001"
    environment: { MINIO_ROOT_USER: minioadmin, MINIO_ROOT_PASSWORD: minioadmin }
    ports: ["9000:9000", "9001:9001"]
  polaris:
    image: apache/polaris:latest
    depends_on: [minio]
    ports: ["8181:8181", "8182:8182"]
    environment:
      AWS_REGION: us-east-1
      AWS_ACCESS_KEY_ID: minioadmin
      AWS_SECRET_ACCESS_KEY: minioadmin
      POLARIS_BOOTSTRAP_CREDENTIALS: POLARIS,root,<root-secret>
      polaris.realm-context.realms: POLARIS
Enter fullscreen mode Exit fullscreen mode

With this file Polaris holds its state in memory and comes up empty after every restart. A production install backs it with Postgres. Once both containers are running, create the bucket, the catalog and the principal through the management API:

P=http://localhost:8181

# 1. A bucket for the tables
aws --endpoint-url http://localhost:9000 s3 mb s3://lakehouse

# 2. A root token
TOKEN=$(curl -s $P/api/catalog/v1/oauth/tokens -H 'Polaris-Realm: POLARIS' \
  -d grant_type=client_credentials -d client_id=root -d client_secret=<root-secret> \
  -d scope=PRINCIPAL_ROLE:ALL | jq -r .access_token)
H=(-H "Authorization: Bearer $TOKEN" -H 'Polaris-Realm: POLARIS' -H 'Content-Type: application/json')

# 3. The catalog: where the files go, and how Polaris and the engines reach the store
curl -s "${H[@]}" $P/api/management/v1/catalogs -d '{"catalog": {
  "name": "olake", "type": "INTERNAL", "readOnly": false,
  "properties": {"default-base-location": "s3://lakehouse/olake"},
  "storageConfigInfo": {"storageType": "S3", "allowedLocations": ["s3://lakehouse/olake"],
    "endpoint": "http://<minio-host>:9000/", "endpointInternal": "http://lake-minio:9000",
    "pathStyleAccess": true, "region": "us-east-1"}}}'

# 4. A principal for OLake Go and the engines. Keep clientId and clientSecret from the response.
curl -s "${H[@]}" $P/api/management/v1/principals -d '{"principal": {"name": "olake"}}'

# 5. Roles, and the grant that lets the principal create namespaces and tables
curl -s "${H[@]}" $P/api/management/v1/principal-roles -d '{"principalRole": {"name": "olake_role"}}'
curl -s "${H[@]}" $P/api/management/v1/catalogs/olake/catalog-roles -d '{"catalogRole": {"name": "olake_catalog_role"}}'
curl -s -X PUT "${H[@]}" $P/api/management/v1/principals/olake/principal-roles -d '{"principalRole": {"name": "olake_role"}}'
curl -s -X PUT "${H[@]}" $P/api/management/v1/principal-roles/olake_role/catalog-roles/olake -d '{"catalogRole": {"name": "olake_catalog_role"}}'
curl -s -X PUT "${H[@]}" $P/api/management/v1/catalogs/olake/catalog-roles/olake_catalog_role/grants -d '{"type": "catalog", "privilege": "CATALOG_MANAGE_CONTENT"}'
Enter fullscreen mode Exit fullscreen mode

What to get right in that block:

  • endpoint ends with a slash. Polaris passes this store address to engines along with vended credentials. ClickHouse 26.8 and 26.10 build object paths from it, and when the slash is missing each read comes back as a 404.
  • endpointInternal is the address Polaris itself uses. MinIO needs both values, and on real S3 you leave both out.
  • No underscores in hostnames. Java's URI parser, which Polaris relies on, rejects a host such as lab_minio.
  • The secret is shown once. Call 4 returns clientId and clientSecret, used from here on as <client_id>:<client_secret>.

Test the principal by trading its credentials for a token, the call OLake Go makes on each sync. A JSON object with an access_token means it works:

curl -s http://localhost:8181/api/catalog/v1/oauth/tokens -H 'Polaris-Realm: POLARIS' \
  -d grant_type=client_credentials -d client_id=<client_id> -d client_secret=<client_secret> \
  -d scope=PRINCIPAL_ROLE:ALL
Enter fullscreen mode Exit fullscreen mode

Step 3: Start OLake UI and add MongoDB as the source

curl -sSL https://raw.githubusercontent.com/datazip-inc/olake-ui/master/docker-compose-v1.yml | docker compose -f - up -d
Enter fullscreen mode Exit fullscreen mode

Open http://localhost:8000 and log in with admin / password. Under Sources, click Create Source and choose MongoDB.

Keep Enable CDC on. My form had one host, host.docker.internal:27017, because MongoDB ran in another container. The other fields were Database Name shop, Auth DB admin, username olake, Replica Set rs0 and Read Preference primary.

OLake UI source form for MongoDB on OLake Go v1.1.0 with Enable CDC on, host host.docker.internal:27017, database shop, auth DB admin, user olake and replica set rs0

Click Set up source. OLake Go tests the connection, checks that the server is a replica set and that a change stream opens, and reports how long the oplog window is. If a check fails, the dialog names the setting and the value it recommends.

Step 4: Add Polaris as the destination

Under Destinations, click Create Destination. Pick Apache Iceberg as the connector, Polaris as the catalog type and OAuth2 as the authentication type, then fill in the rest:

Field Value in my run
REST Catalog URI http://host.docker.internal:8181/api/catalog
Polaris Catalog Name olake
REST Auth URI http://host.docker.internal:8181/api/catalog/v1/oauth/tokens
REST Credential <client_id>:<client_secret>
REST scope PRINCIPAL_ROLE:ALL
AWS Region us-east-1
S3 Endpoint http://host.docker.internal:9000
AWS Access Key, AWS Secret Key the MinIO keys

OLake UI destination form for Apache Iceberg with catalog type Polaris, OAuth2 authentication, the REST catalog URI, Polaris catalog name olake, the MinIO S3 endpoint and region us-east-1

Create runs a real write test. OLake Go gets a token, creates a namespace and a test table through Polaris, writes to the bucket and drops the test table again.

Step 5: Create the job and run the first sync

Under Jobs, click Create Job, name it mongodb_to_clickhouse and pick a schedule. The schedule decides how often the change stream is drained, not how often a full copy runs.

Select the source and the destination. Under Advanced Settings, set Target Query Engines to ClickHouse, DuckDB and Trino. From that list OLake Go resolves a delete format every one of them can read, and here it resolved equality deletes, which need no index between runs.

Click Next. On the Streams page tick customers and orders, set each to Full Refresh + CDC with ingestion mode Upsert, and leave Upsert Type as resolved. Then click Create Job, open the job's menu and choose Sync Now.

OLake UI Streams page with customers and orders from the shop database selected, sync mode Full Refresh + CDC, ingestion mode Upsert and upsert type Equality Deletes on Iceberg format version V2

The first run copied 8 customers and 40 orders, 48 documents and 6.40 KB in all, in 15 seconds with container start included. The job opens the change stream and saves its resume token before the copy starts, so nothing written during the snapshot is lost.

The destination namespace is built from the job name and the source database, which gives mongodb_to_clickhouse_shop. To change it, edit the Iceberg DB field at the top of the Streams page before the first sync.

Step 6: Attach the catalog in ClickHouse and query

No table has to be registered. In clickhouse-client:

SET allow_database_iceberg = 1;

CREATE DATABASE polaris
ENGINE = DataLakeCatalog('http://<polaris-host>:8181/api/catalog')
SETTINGS
  catalog_type = 'rest',
  warehouse = 'olake',
  catalog_credential = '<client_id>:<client_secret>',
  oauth_server_uri = 'http://<polaris-host>:8181/api/catalog/v1/oauth/tokens',
  auth_scope = 'PRINCIPAL_ROLE:ALL',
  vended_credentials = true,
  region = 'us-east-1';

SHOW TABLES FROM polaris;

SELECT _id, name, city, tier
FROM polaris.`mongodb_to_clickhouse_shop.customers`
ORDER BY _id;
Enter fullscreen mode Exit fullscreen mode

Three details in that statement:

  • The backticks. ClickHouse has one level of namespace, so the Iceberg namespace and the table name sit together inside one quoted identifier.
  • vended_credentials = true. ClickHouse reads the files with short-lived keys that Polaris issues per table, so no store keys are kept in ClickHouse.
  • Read-only. INSERT, ALTER and RENAME DATABASE on this database return NOT_IMPLEMENTED.

Money needs one more step. A Decimal128 field such as amount arrives as String, so cast it before you sum:

SELECT status, count() AS n, round(sum(toDecimal64(amount, 2)), 2) AS total
FROM polaris.`mongodb_to_clickhouse_shop.orders`
GROUP BY status ORDER BY status;
Enter fullscreen mode Exit fullscreen mode

Leave the cast out and ClickHouse answers Illegal type String of argument for aggregate function sum. My first roll-up hit exactly that.

Step 7: Change documents in MongoDB and sync again

Back in mongosh, on database shop, make 12 changes: 7 inserts and 5 updates.

const now = new Date();
db.customers.insertMany([
  { _id: 9,  name: 'Maya Patel',  email: 'maya@example.com',  city: 'Pune',      tier: 'silver', created_at: now, updated_at: now },
  { _id: 10, name: 'Lucas Silva', email: 'lucas@example.com', city: 'São Paulo', tier: 'bronze', created_at: now, updated_at: now }
]);
db.orders.insertMany([
  { _id: 41, customer_id: 9,  product: 'Laptop',   amount: NumberDecimal('1299.00'), status: 'placed', created_at: now, updated_at: now },
  { _id: 42, customer_id: 9,  product: 'Mouse',    amount: NumberDecimal('25.50'),   status: 'placed', created_at: now, updated_at: now },
  { _id: 43, customer_id: 10, product: 'Monitor',  amount: NumberDecimal('349.99'),  status: 'placed', created_at: now, updated_at: now },
  { _id: 44, customer_id: 3,  product: 'Keyboard', amount: NumberDecimal('89.00'),   status: 'placed', created_at: now, updated_at: now },
  { _id: 45, customer_id: 7,  product: 'Webcam',   amount: NumberDecimal('79.90'),   status: 'placed', created_at: now, updated_at: now }
]);
db.customers.updateOne({ name: 'Liam Carter' }, { $set: { tier: 'gold', updated_at: now } });
db.customers.updateOne({ name: 'Zara Ali' },    { $set: { city: 'Abu Dhabi', updated_at: now } });
db.orders.updateMany({ _id: { $in: [1, 4, 7] } }, { $set: { status: 'delivered', updated_at: now } });
Enter fullscreen mode Exit fullscreen mode

Choose Sync Now again. The second sync read 12 change events (1.60 KB) from the stream and finished in 8 seconds.

OLake UI job history for mongodb_to_clickhouse with two completed syncs, the first taking 15 seconds and the second 8 seconds

The sync log carries a commit report per collection. For customers it reads addedDataFiles=1, addedRecords=4, addedEqualityDeleteFiles=1 and addedEqualityDeletes=2. That is one data file holding the 2 inserts and the new versions of the 2 updated documents, and one small delete file that retires the 2 old versions by key.

orders has the same shape, with 8 rows and 3 deletes.

OLake UI sync log filtered to the Iceberg commit report for orders: addedDataFiles 1, addedEqualityDeleteFiles 1, addedRecords 8, totalRecords 48 and addedEqualityDeletes 3

Run the SELECT from step 6 again. There is nothing to refresh: Liam Carter is gold, Zara Ali is in Abu Dhabi, and Maya Patel and Lucas Silva have joined, which makes 10 rows with one per _id.

clickhouse-client querying the customers table in the polaris database and returning 10 rows with _id, name, city and tier after the change sync

Each table also carries columns OLake Go adds, among them _op_type: r for a snapshot row, c for an insert, u for an update and d for a delete. On MongoDB tables there is _cdc_resume_token too, the change stream token each change came from.

Schema changes. A field that shows up in new documents becomes a column on the next sync, and ClickHouse shows it the next time the table is opened, with nulls for older rows. A field whose type changes in an incompatible way fails the sync rather than corrupt the table.

Read the same tables from DuckDB and Trino

Neither engine needs an export. DuckDB attaches Polaris with the principal's client id and secret, and fetches the token itself:

INSTALL iceberg; LOAD iceberg;
INSTALL httpfs;  LOAD httpfs;

CREATE SECRET polaris_secret (
  TYPE iceberg,
  CLIENT_ID '<client_id>', CLIENT_SECRET '<client_secret>',
  OAUTH2_SERVER_URI 'http://<polaris-host>:8181/api/catalog/v1/oauth/tokens',
  OAUTH2_SCOPE 'PRINCIPAL_ROLE:ALL'
);
-- MinIO, or any store whose address differs from the one Polaris vends
CREATE SECRET store_secret (
  TYPE s3, KEY_ID '<access key>', SECRET '<secret key>',
  ENDPOINT '<minio-host>:9000', URL_STYLE 'path', USE_SSL false, REGION 'us-east-1'
);

ATTACH 'olake' AS polaris (
  TYPE iceberg,
  ENDPOINT 'http://<polaris-host>:8181/api/catalog',
  SECRET polaris_secret,
  ACCESS_DELEGATION_MODE 'none'
);

SELECT _id, name, city, tier FROM polaris.mongodb_to_clickhouse_shop.customers ORDER BY _id;
Enter fullscreen mode Exit fullscreen mode

store_secret and ACCESS_DELEGATION_MODE 'none' are for a laptop, where the store address Polaris hands out may not resolve. With Polaris on AWS S3, remove both and DuckDB reads with the vended credentials.

Trino needs one catalog properties file, etc/catalog/polaris.properties:

connector.name=iceberg
iceberg.catalog.type=rest
iceberg.rest-catalog.uri=http://<polaris-host>:8181/api/catalog
iceberg.rest-catalog.warehouse=olake
iceberg.rest-catalog.security=OAUTH2
iceberg.rest-catalog.oauth2.credential=<client_id>:<client_secret>
iceberg.rest-catalog.oauth2.scope=PRINCIPAL_ROLE:ALL
iceberg.rest-catalog.oauth2.server-uri=http://<polaris-host>:8181/api/catalog/v1/oauth/tokens
iceberg.rest-catalog.vended-credentials-enabled=true
fs.native-s3.enabled=true
s3.region=us-east-1
# MinIO or another S3-compatible store only:
s3.endpoint=http://<minio-host>:9000
s3.path-style-access=true
Enter fullscreen mode Exit fullscreen mode

The SELECT is the same one DuckDB ran.

Trino 484 command line client querying customers in the polaris catalog and returning the same 10 rows as ClickHouse

DuckDB 1.5.5 and Trino 484 gave back the same 10 rows as ClickHouse. An orders roll-up matched MongoDB to the cent in all three, each casting amount first: 16 delivered orders for 8659.68, 18 placed for 10522.26 and 11 shipped for 6397.25.

Tips and limits from the run

  • Documents are flattened one level. Nested objects and arrays arrive as JSON text in a String column, which you parse with JSONExtract or JSONExtractString. If every query would start that way, ClickHouse's own JSON column type on a MergeTree table may serve you better.
  • An ObjectId key becomes its 24-character hex string. The integer _id keys in this run arrived as Nullable(Int32), and a MongoDB date as Nullable(DateTime64(6, 'UTC')).
  • There is no primary index. A DataLakeCatalog query reads Parquet over the network. For a dashboard that needs sub-second answers, load the hot slice into a MergeTree table on a schedule.
  • Nothing compacts the tables for you. Each sync adds a small data file and a delete file per collection. Spark's rewrite_data_files works through the same Polaris endpoint.
  • No deletion vectors on ClickHouse 26.8. That LTS release reads positional and equality deletes only, so keep the upsert type OLake Go resolves.
  • The oplog is sized in gigabytes, not hours. A write-heavy cluster shortens the window, so check it after a busy day.

How the methods compare

Method Freshness Updates and deletes Where the data lands What you run
ClickPipes for MongoDB CDC through change streams Yes, into ReplacingMergeTree ClickHouse Cloud tables with documents as JSON; one reader Nothing; ClickHouse Cloud only, billed per ClickPipe
MongoDB table engine Live, per query Reads the current document Nothing is copied; each query hits MongoDB A MongoDB user for ClickHouse
Debezium, Kafka, Kafka engine Seconds Yes, with your own merge logic Kafka topics, then ClickHouse tables Kafka, Kafka Connect, Debezium, a view per collection
Managed ELT Minutes, by plan Varies by tool ClickHouse tables, a second copy Nothing; per row, per GB or per connector
OLake Go to Polaris (this post) CDC on a schedule down to one minute Yes, as Iceberg row-level deletes Iceberg tables for ClickHouse, DuckDB, Trino and Spark One Docker Compose stack, open source; your bucket and compute

On ClickHouse Cloud, with ClickHouse as the only reader and MergeTree speed required, ClickPipes is the simpler choice. The Iceberg route pays off once another engine needs the same rows, or when you want to own the files and the catalog.

FAQ

Do I have to refresh the ClickHouse database after each sync?

No. Each sync ends with one commit to Polaris, and ClickHouse picks up the new snapshot on its next query. No engine keeps a copy of the data, so there is nothing to reload.

Can I run the pipeline without OLake UI?

Yes, with the olakego/source-mongodb:latest image. check tests your source.json, discover writes the stream files, and sync runs the job with sync_mode set to cdc and update_type set to eq. Later runs add --state /mnt/config/state.json, so only the changes since the previous run are replayed.

What happens if the job is paused for longer than the oplog window?

The saved resume token is no longer in the oplog, so the stream cannot resume and the job needs a fresh snapshot. The source test reports the current window and warns when it is under 7 days. Size the oplog for your longest planned pause.

Where to go from here

  • Point the source at Atlas: one SRV host with Use SRV on, and the minimum oplog window set to cover your longest pause between syncs.
  • Replace MinIO with an S3 bucket and an Identity and Access Management (IAM) role, and put Postgres behind Polaris so the catalog survives a restart.
  • The full guide, with the complete data type table and the troubleshooting list, is on olake.io.

If a step behaves differently on your machine, leave a comment and I will correct the post.

Top comments (0)