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
ReplacingMergeTreetables 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
shopwith two collections,customersandorders. - 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
DataLakeCatalogengine, 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 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) 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); Two notes before you go on:
- Atlas. The replica set and the oplog already exist. Create the user under Database Access with
readon your database plusclusterMonitor, 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 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"}' What to get right in that block:
-
endpointends 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. -
endpointInternalis 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
clientIdandclientSecret, 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 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 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.
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 |
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.
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; 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,ALTERandRENAME DATABASEon this database returnNOT_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; 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 } }); Choose Sync Now again. The second sync read 12 change events (1.60 KB) from the stream and finished in 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.
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.
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; ...







