BigQuery wants columns, and MongoDB hands you documents that get rewritten in place. A MongoDB to BigQuery pipeline has to close both gaps: turn fields into columns, and carry every update and delete across instead of shipping yesterday's export.
The common ways to move the data:
-
mongoexportto JSON, thenbq load. A script, a scheduler and a staging bucket. Freshness is hours to daily, and every run is a full reload, so updates and deletes never arrive as changes. - Datastream for MongoDB. Google's managed service reads change streams into native BigQuery datasets, near real time by Google's description. There is nothing to run, and BigQuery is the only reader of the result.
- Debezium, Kafka and a BigQuery sink. Changes arrive in seconds, and you operate Kafka, Kafka Connect, Debezium and a sink connector per collection.
- Managed extract, load, transform (ELT) tools such as Fivetran, Estuary or Airbyte Cloud. Nothing to host, and freshness in minutes depending on the plan. You pay per row, per GB or per connector for a second copy in BigQuery.
This tutorial takes a fifth route. OLake Go, an open source (Apache 2.0) replication tool, reads the MongoDB change stream with change data capture (CDC) and commits each collection as an Apache Iceberg table into BigLake, Google Cloud's Iceberg representational state transfer (REST) catalog. The files stay in a Cloud Storage bucket you own, and BigQuery reads them in place.
I ran it against MongoDB 7 as a single-node replica set in Docker and a bucket in us-central1, with OLake Go v1.1.0. The first sync copied 48 documents in 34 seconds, and a second sync replayed 12 change events in 33 seconds. Every figure in this post is from that run.
What you need for this MongoDB to BigQuery pipeline
MongoDB 4.0 or later running as a replica set (self-hosted or Atlas), Docker, and a Google Cloud project where you can enable an API and create a service account. The account that runs the BigQuery queries needs the BigQuery Job User role plus read access to the catalog. Set aside about 30 minutes.
Step 1: A replica set, a user and two collections
Change streams exist only in replica set mode, and one node is enough. On a self-hosted server, start mongod with --replSet rs0 and run this in mongosh on the primary:
rs.initiate({ _id: "rs0", members: [{ _id: 0, host: "<host>:27017" }] }) use admin db.createUser({ user: "olake", pwd: "<password>", roles: [{ role: "read", db: "shop" }, { role: "clusterMonitor", db: "admin" }] }) // oplog size in bytes; raise it with replSetResizeOplog if it is small use local db.oplog.rs.stats().maxSize The read role lets OLake Go copy the collections. clusterMonitor (or readAnyDatabase) grants the oplog access that the change stream needs.
Confirm there is one PRIMARY and that the user exists:
rs.status().members.map(m => m.stateStr) db.getSiblingDB("admin").getUsers().users.map(u => u.user) Next, the data. Use your own collections, or seed the same 8 customers and 40 orders I used, with money stored as NumberDecimal:
use shop const seededAt = new Date(); const people = [ [1, 'Aarav Mehta', 'Mumbai', 'gold'], [2, 'Priya Sharma', 'Bengaluru', 'silver'], [3, 'Liam Carter', 'Austin', 'bronze'], [4, 'Sofia Rossi', 'Milan', 'gold'], [5, 'Kenji Tanaka', 'Tokyo', 'silver'], [6, 'Emma Schulz', 'Berlin', 'bronze'], [7, 'Noah Kim', 'Seoul', 'gold'], [8, 'Zara Ali', 'Dubai', 'silver'] ]; db.customers.insertMany(people.map(([id, name, city, tier]) => ({ _id: id, name, email: name.split(' ')[0].toLowerCase() + '@example.com', city, tier, created_at: seededAt, updated_at: seededAt }))); const products = ['Laptop', 'Headphones', 'Monitor', 'Keyboard', 'Mouse', 'Webcam']; const statuses = ['placed', 'shipped', 'delivered']; db.orders.insertMany(Array.from({ length: 40 }, (_, i) => { const n = i + 1; return { _id: n, customer_id: 1 + (n % 8), product: products[n % 6], amount: NumberDecimal((20 + ((n * 7919) % 120000) / 100).toFixed(2)), status: statuses[n % 3], created_at: seededAt, updated_at: seededAt }; })); On Atlas, skip rs.initiate, because clusters are already replica sets. Create the user under Database Access with the same two roles, 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 of it by default, and a job paused past that window cannot resume and needs a fresh snapshot.
Step 2: Bucket, service account and key on Google Cloud
All of this happens in the Google Cloud console.
- Enable the BigLake API under APIs and services, Enable APIs and services.
- Create a bucket in Cloud Storage, in the region where BigQuery will run the queries. Its name becomes the catalog name in BigQuery SQL, so choose one you do not mind typing.
- Create a service account under IAM and Admin, Service Accounts. IAM is short for Identity and Access Management. Grant the account BigLake Editor on the project and Storage Object User on the bucket.
- Download a JSON key from the service account's Keys tab: Add key, Create new key, JSON. The console hands it over once.
You do not create the catalog yourself. BigLake makes a single-bucket catalog named after the bucket the first time OLake Go calls the endpoint with gs://<bucket> as the catalog path.
Step 3: Start OLake UI and connect MongoDB
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 sign in with admin / password.
Go to Sources, Create Source and pick MongoDB. Leave Enable CDC on, then fill in the connection details. Mine were host host.docker.internal:27017 (MongoDB ran in another container), Database Name shop, Auth DB admin, user olake and Replica Set rs0, with Read Preference left on primary.
Click Set up source. OLake Go tests the connection, confirms that it can open a change stream, and reports the oplog window. A window under 7 days is shown as a warning, not a blocker.
Step 4: Point the destination at BigLake
Go to Destinations, Create Destination, choose Apache Iceberg as the connector and BigLake as the catalog type.
| Field | Value |
|---|---|
| REST Catalog URI | https://biglake.googleapis.com/iceberg/v1/restcatalog |
| BigLake Catalog Path | gs://<bucket>, with no folder after it |
| Authentication Type | GCP |
| GCP Service Account JSON | the full contents of the key file |
| Catalog Name | olake_iceberg |
| GCP Project ID | your project ID |
| Enable Arrow Writes | off |
Create runs a test: OLake Go calls the endpoint, creates the catalog on first contact, then writes and drops a test table in the bucket. A missing role fails this test with a 403 from biglake.googleapis.com or storage.googleapis.com, and the host tells you which grant to add.
⚠️ Keep the catalog in its default end-user credential mode. OLake Go 1.1.0 does not send the
X-Iceberg-Access-Delegationheader, so a catalog switched to vended credentials rejects its commits.
Step 5: Create the job and run the first sync
Open Jobs, click Create Job, name it mongodb_to_bigquery, set a schedule and select the source and destination.
Under Advanced Settings, set Target Query Engines to Google BigQuery, Apache Spark and DuckDB. OLake Go then offers only the delete formats all three can read, which are equality and positional deletes. Deletion vectors drop off the list because BigQuery reads them only in preview.
Click Next, tick customers and orders, and keep Full Refresh + CDC with Upsert. The Upsert Type in my run was Positional Deletes. Then click Create Job, and choose Sync Now from the job's menu.
The first sync copied 8 customers and 40 orders (48 documents, 6.40 KB) in 34 seconds, container start included. It opened the change stream and saved a resume token before reading the collections in parallel chunks, so writes made during the copy are not lost.
OLake Go names the BigLake namespace after the job and the source database, which gave mongodb_to_bigquery_shop. The Iceberg DB field at the top of the Streams page changes that before the first sync.
Step 6: Query the collections in BigQuery
There is no dataset to create and no external table to declare. In BigQuery the bucket is the catalog, the namespace is the dataset, and you address a table by a four-part name in backticks:
SELECT _id, name, city, tier FROM `<project-id>.<bucket>.mongodb_to_bigquery_shop.customers` ORDER BY _id; SELECT status, count(*) AS n, round(sum(cast(amount AS NUMERIC)), 2) AS total FROM `<project-id>.<bucket>.mongodb_to_bigquery_shop.orders` GROUP BY status ORDER BY status; Two details matter. Run the query in the bucket's region, which you set in the editor under More, Query settings. And cast amount, because a Decimal128 field arrives in BigQuery as STRING.
From a terminal, the same statements run with bq:
bq query --project_id=<project-id> --location=<region> --use_legacy_sql=false "<sql>" Step 7: Change documents and sync again
Now the part a nightly export cannot do. 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 } }); Click Sync Now again. The second sync read 12 change events (1.60 KB) from the stream and finished in 33 seconds.
For customers, OLake Go wrote one new data file holding 4 rows: the 2 inserts and the new versions of the 2 updated documents. One small positional delete file retires the 2 old versions. The commit report in the sync log says the same thing: addedDataFiles=1, addedRecords=4, addedPositionalDeleteFiles=1, addedPositionalDeletes=2.
orders has the same shape, with 8 rows and 3 deletes. Rerun the first SELECT in BigQuery, with no refresh and no ALTER TABLE:
Liam Carter is gold, Zara Ali has moved to Abu Dhabi, and customers 9 and 10 are present. BigQuery applies the positional deletes while reading, so each key still returns one row. Add _op_type to the query to see how each row arrived: r for the snapshot, c for an insert and u for an update.
Read the same tables from DuckDB
No export is involved here. DuckDB attaches the BigLake catalog with a Google access token and reads the files OLake Go wrote.
Because the catalog is in end-user mode, DuckDB brings its own storage credentials. That is a hash-based message authentication code (HMAC) key for the service account, created under Cloud Storage, Settings, Interoperability.
INSTALL iceberg; LOAD iceberg; INSTALL httpfs; LOAD httpfs; -- gcloud auth print-access-token, or a token minted for the service account CREATE SECRET biglake_catalog ( TYPE iceberg, TOKEN '<access token>', EXTRA_HTTP_HEADERS MAP {'x-goog-user-project': '<project-id>'} ); -- the HMAC key pair for the bucket CREATE SECRET biglake_files (TYPE gcs, KEY_ID '<hmac access id>', SECRET '<hmac secret>'); ATTACH 'gs://<bucket>' AS biglake ( TYPE iceberg, ENDPOINT 'https://biglake.googleapis.com/iceberg/v1/restcatalog', SECRET biglake_catalog ); SHOW ALL TABLES; SELECT _id, name, city, tier FROM biglake.mongodb_to_bigquery_shop.customers ORDER BY _id; DuckDB 1.5.5 returned the same 10 customers as BigQuery, and Spark 4.0.1 with Iceberg 1.10.0 did as well. The orders roll-up matched MongoDB to the cent in all three engines: 16 delivered orders for 8659.68, 18 placed for 10522.26 and 11 shipped for 6397.25. In DuckDB and Spark the cast is sum(cast(amount AS decimal(12,2))).
The access token lasts an hour. When a query fails with 401, run CREATE OR REPLACE SECRET with a fresh one.
Tips from the run
- Documents are flattened one level. Top-level fields become columns. Nested objects and arrays arrive as JSON text in a
STRINGcolumn, whichPARSE_JSONorJSON_VALUEcan unpack. - Store doubles if you want to skip the cast.
Decimal128always arrives as text, and anObjectIdkey arrives as its 24-character hex string. - A new field becomes a new column on the next sync, with nulls for older rows. A field whose type changes in an incompatible way fails the sync instead of corrupting the table.
- Watch
metadata.json. BigLake keeps every snapshot in it and rejects a file above 1 MB, which a busy table reaches after a few thousand syncs. Expire snapshots and compact on a schedule with Spark'sexpire_snapshotsandrewrite_data_files.
How the MongoDB to BigQuery options compare
| Method | Freshness | Updates and deletes | Where the data lands | What you run |
|---|---|---|---|---|
mongoexport plus bq load | hours to daily | no, full reloads only | native BigQuery tables | a script, a scheduler, a staging bucket |
| Datastream for MongoDB | near real time, by Google's description | yes | native BigQuery datasets | nothing; a stream in the console |
| Debezium, Kafka, BigQuery sink | seconds | yes, in upsert mode | Kafka topics, then BigQuery tables | Kafka, Kafka Connect, Debezium, sinks |
| Managed ELT | minutes, by plan | varies by tool | a second copy in BigQuery | nothing; per row, GB or connector pricing |
| OLake Go to BigLake (this post) | CDC on a schedule down to one minute | yes, as row-level deletes | open tables BigQuery, Spark and DuckDB read | one Docker Compose stack, your bucket |
Datastream is the simpler choice when BigQuery is the only reader and you prefer a managed Google service. The route in this post has two more limits worth stating plainly:
- A catalog table is read from Parquet in the bucket on every query, so it will not match native BigQuery speed. Load the hot slice into a native table on a schedule if a dashboard needs that.
- Deletion vectors are out while BigQuery is a reader. BigQuery reads them only in preview, with a cap of 100,000 deletion vector entries per query.
FAQ
How fresh can the BigQuery tables be?
As fresh as the job's schedule, which goes down to one minute. Each run drains the change stream and ends with one commit to BigLake, and BigQuery sees that snapshot on its next query. It is CDC on a schedule, not a continuous stream.
Can I run this from the command line instead of the UI?
Yes. The olakego/source-mongodb:latest image has check, discover and sync commands driven by JSON config files. Positional deletes keep a small index between runs, so mount a persistent directory through OLAKE_INDEX_DB_DIR and pass --state on every run after the first.
What does it cost to keep running?
Storage is billed at Cloud Storage rates for the Parquet and delete files, and the BigLake catalog has no per-table charge. BigQuery bills queries by bytes scanned on demand, or by slot time on an edition. OLake Go runs on whatever machine hosts Docker.
Where to go from here
- Point the source at your real replica set or Atlas cluster. On Atlas, paste the cluster host with Use SRV on.
- The full guide, with the CLI configs, the Spark connection and the complete data type table, is on olake.io.
If something here does not match what you see, post the exact message in the comments.










