MongoDB Sink Connector
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
The Debezium MongoDB sink connector reads change events that Debezium relational source connectors write to Kafka and applies them to collections in a MongoDB database, one document per source row. It is the document-database counterpart of the JDBC Sink Connector: no application code, and idempotent writes keyed by the source primary key.
In a migration it covers the relational-to-document direction. The Bookshop example moves the legacy MongoDB
bookshop.reviews collection into the PostgreSQL table book_review (see
MongoDB Connector). This page shows the other direction: changes to
book_review in PostgreSQL flowing back into MongoDB, and a MongoDB read model of the legacy Oracle BOOK table. It
also explains the limits that decide when the sink is enough and when a translating consumer is needed.
Checked on 2026-11-09 against Debezium 3.7.1.Final (the MongoDB sink ships in the debezium-connector-mongodb
plug-in), Apache Kafka 4.3 (Kafka Connect), PostgreSQL 18 and MongoDB 8.0. The configuration on this page is derived
from the official documentation; the connector class name, the write operations and the BSON conversions described
below were checked against the classes in the 3.7.1.Final debezium-connector-mongodb JAR. The connectors on this
page were not run.
When a document target helps in a migration
A relational-to-document sink is useful in three situations:
-
Reverse replication of a document store. After the write cut-over of reviews, the new application writes
book_reviewin PostgreSQL, and the legacy application still reads MongoDB until it is retired. The sink keeps a MongoDB copy current (with the limits described in Writing back to the legacyreviewscollection). -
A document read model built from a relational source. A catalogue service that serves book documents can be fed from the legacy
BOOKSHOP.BOOKtable while the migration is still in progress, without touching the legacy application. This is the CQRS use of change events described in CQRS. -
A relational database replaced by MongoDB. When the new system itself uses MongoDB, the sink provides the 1:1 copy of the tables that keep their shape, and translators build the remodelled documents, in the same way as with the JDBC sink.
How the connector works
For each record the connector resolves the target collection from the topic, builds the document _id from the
record key, and adds a write operation to a bulk write against that collection. The operation depends on the op of
the change event:
| Event | Official description | Write operation in 3.7.1.Final |
|---|---|---|
Create ( |
Create document |
|
Update ( |
Modify the document with the specified identifier |
|
Delete ( |
Remove the document with the specified identifier |
|
Tombstone ( |
— |
Skipped (tombstones exist for Kafka log compaction) |
Three consequences follow from these operations:
-
Writes are idempotent. A replayed create or update replaces the document with the same state again, and a replayed delete finds nothing to delete. Kafka Connect delivers records at least once, so this is what keeps a restart or a rebalance harmless, as explained for the JDBC sink in at-least-once delivery.
-
The whole document is replaced. An update does not patch fields; the document becomes the
afterstate of the row. Fields that another writer added to the document in MongoDB are lost at the next update of that row. Treat the target collection as owned by the sink. -
Truncates are not applied. Only create, read, update and delete events are handled.
The connector processes the events of a partition in order, and the source connectors key events by primary key, so all changes of one row are applied in commit order. It gives no transactional guarantee across events or documents: a legacy transaction that changed three rows becomes three independent writes, and a reader can see the first before the third.
Limitations
-
Relational sources only. The connector consumes events from the Debezium connectors for MariaDB, MySQL, Oracle, PostgreSQL and SQL Server. It cannot consume events from the Debezium MongoDB source connector, so it is not a tool for MongoDB-to-MongoDB migrations (in those events
afteris a JSON string, not a structure). -
Native envelopes only. The value must be a Debezium change event with a
before/afterstructure. Do not apply the event flattening SMT before this sink; the connector rejects values without a non-emptyafterdocument for inserts and updates. The connector can also unwrap events that the source wrote in CloudEvents format (see CloudEvents input). -
Limited schema evolution. MongoDB has no table schema, so new columns simply appear in the documents written after the change. Renamed or dropped columns are not cleaned up in documents written earlier; that needs a migration script on the MongoDB side.
-
No metrics. The official documentation states that this release of the connector does not expose any metrics.
Installing the connector
The sink is part of the MongoDB connector plug-in archive (debezium-connector-mongodb), not a separate download, and
it uses the MongoDB Java driver that the archive contains. The quay.io/debezium/connect:3.7.1.Final image includes
that plug-in, so the Compose stacks in this section can use it directly.
The official page gives the connector class as io.debezium.connector.mongodb.sink.MongoDbSinkConnector. In the
3.7.1.Final JAR the class registered as a Kafka Connect sink is io.debezium.connector.mongodb.MongoDbSinkConnector
(the sink package holds the task and its helpers). Check what your worker reports before you register the
connector, and use that name:
curl -s http://localhost:8083/connector-plugins | jq -r '.[] | select(.type == "sink") | .class'
# io.debezium.connector.jdbc.JdbcSinkConnector
# io.debezium.connector.mongodb.MongoDbSinkConnector
# ...
Reference: Debezium — MongoDB sink quick start
Unlike the MongoDB source connector, the sink does not need a replica set: it only writes. The user in the connection
string needs the readWrite role on the target database.
// mongosh, connected to the MongoDB deployment as an administrator
use admin
db.createUser({
user: "bookshop_sync",
pwd: "change-me",
roles: [
{ role: "readWrite", db: "bookshop" },
{ role: "readWrite", db: "catalogue" }
]
})
Reference: MongoDB — Built-in roles
Configuration properties
The official documentation groups the properties as follows.
Kafka Connect sink properties
| Property | Default | Description |
|---|---|---|
|
none |
The MongoDB sink connector class (see Installing the connector). |
|
|
Maximum number of tasks. |
|
none |
The topics to consume, as a list or as a regular expression. |
MongoDB connection properties
| Property | Default | Description |
|---|---|---|
|
none |
Standard MongoDB connection string (URI) of the target deployment, for example |
|
none |
Name of the target MongoDB database. All collections of one connector are in this database. |
Sink behaviour properties
| Property | Default | Description |
|---|---|---|
|
|
Strategy that derives the collection name. The default takes the topic name and replaces dots with underscores. A custom |
|
|
Template for the collection name. |
|
|
Strategy that names the document fields. The default uses the original field name. |
Common sink options
| Property | Default | Description |
|---|---|---|
|
empty |
Comma-separated fields of the event value to include, as |
|
empty |
Comma-separated fields of the event value to exclude, in the same form. Not with |
|
|
Maximum number of records written in one batch. |
CloudEvents option
| Property | Default | Description |
|---|---|---|
|
|
Regular expression that identifies CloudEvents records by their schema name. |
The Kafka Connect error handling properties (errors.tolerance, errors.deadletterqueue.topic.name and the others
listed on the JDBC sink page)
apply to every sink connector. They cover failures in the converter and transformation stages. The official MongoDB
sink documentation does not describe sending failed MongoDB writes to a dead-letter queue, so plan for a failed bulk
write to fail the task, and watch the task status.
Collection names
With the defaults, the collection name is the topic name with dots replaced by underscores: topic
modern.public.book_review becomes the collection modern_public_book_review in sink.database. That is rarely the
name you want in a migration. Set collection.name.format to a literal name when the connector reads a single topic,
or to a template with a prefix or suffix (for example mirror_${topic}). The default naming strategy is the same
shared class that the JDBC sink uses, which also resolves ${source.table}-style placeholders from the source block,
but the MongoDB sink documentation only describes ${topic}; the examples on this page use literal names, one topic
per connector.
Because one connector writes to a single database (sink.database), use one connector per target database. The
Bookshop examples use two connectors for that reason.
From keys to _id
The record key becomes the _id of the document, and updates and deletes find the document by that _id. Debezium
relational source connectors key each event with a structure of the table’s primary key columns, so the _id is an
embedded document, even for a single-column key:
_id// Kafka record key of a change to book_review (PostgreSQL primary key: id text,
// which holds the legacy MongoDB _id as extended JSON)
{ "id": "{\"$oid\": \"6af189a0c788084b3fbe7dcc\"}" }
// _id of the MongoDB document written by the sink
{ "_id": { "id": "{\"$oid\": \"6af189a0c788084b3fbe7dcc\"}" }, ... }
// Composite key, for example ORDER_LINE (ORDER_ID, LINE_NO) from bookshop-oracle-source,
// whose decimal.handling.mode=string turns every NUMBER into a string
{ "_id": { "ORDER_ID": "900017", "LINE_NO": "2" }, ... }
Reference: Debezium — MongoDB sink key field mapping
What this means in practice:
-
Query the documents with the embedded
_id(db.book_review.find({ "_id.id": '{"$oid": "6af1..."}' })or an exact match on the whole embedded document). An exact match on an embedded document depends on field order, which the sink takes from the key schema. -
A source table without a primary key produces events with a
nullkey, and the sink cannot build an_idfor them. Give such a table a key in the source connector withmessage.key.columns. -
Changing the source key (an SMT that rewrites the key, a different primary key after a legacy schema change) creates new documents next to the old ones. Keep the key stable for the life of the migration.
-
Other
_idshapes, such as a plain string or the original MongoDBObjectId, are not described in the official documentation. If you need them, write the documents with a consumer (see Listening to Events in Applications).
How values become BSON
The document body is the after structure of the event, one field per column, with the column names as they are in
the source (BOOK_ID stays upper case; use column.naming.strategy to change that). The value conversion follows
the Kafka Connect schema of each field. In the 3.7.1.Final classes the converter maps the primitive types to the
matching BSON types (integers, doubles, booleans, strings, binary), and gives special treatment to exactly four Kafka
Connect logical types: Decimal becomes Decimal128, and Date, Time and Timestamp become BSON dates.
The Debezium logical types are not converted; they are written in their primitive representation:
| Source column | Event schema | Stored in MongoDB as |
|---|---|---|
PostgreSQL |
|
string |
PostgreSQL |
|
string (the JSON text, not an embedded document) |
PostgreSQL |
|
|
PostgreSQL |
|
ISO-8601 string |
PostgreSQL |
|
32-bit integer |
Oracle |
|
64-bit integer |
Oracle |
|
64-bit integer |
Oracle |
|
string ( |
Oracle |
|
|
Dates stored as numbers are the main surprise: a MongoDB query cannot compare them with ISODate values, and a TTL
index ignores them. There are two ways to get real BSON dates:
-
Set
time.precision.mode=connectin the source connector, so that it emits the Kafka ConnectDate,TimeandTimestamptypes. This changes the events for every consumer of those topics and limits precision to milliseconds (see Data Types & Precision). It is reasonable when MongoDB is the only consumer, or with a dedicated source connector for the MongoDB pipeline. -
Keep the defaults and convert in a consumer that writes MongoDB itself.
Bookshop: book_review back to MongoDB
The reviews were migrated from MongoDB to PostgreSQL. After the write cut-over the new application owns them, and
the bookshop-pg-source connector (topic prefix modern, publication bookshop_reverse_pub, with book_review
added to it by ALTER PUBLICATION bookshop_reverse_pub ADD TABLE book_review) publishes changes to
modern.public.book_review. The table is the one that the lab of the
MongoDB Connector page fills from the legacy collection:
book_review table (as defined on the MongoDB Connector page)CREATE TABLE book_review (
id text PRIMARY KEY, -- the Debezium key: the _id as extended JSON
book_id bigint,
customer_legacy_id bigint,
rating smallint,
title text,
body text,
helpful_votes integer,
created_at timestamptz,
document_json jsonb
);
Reference: Debezium — PostgreSQL data type mappings
bookshop-mongo-reviews-sink.json: PostgreSQL book_review into MongoDB{
"name": "bookshop-mongo-reviews-sink",
"config": {
"connector.class": "io.debezium.connector.mongodb.MongoDbSinkConnector",
"tasks.max": "1",
"topics": "modern.public.book_review",
"mongodb.connection.string": "mongodb://bookshop_sync:change-me@mongo:27017/?authSource=admin",
"sink.database": "bookshop",
"collection.name.format": "book_review",
"batch.size": "2048",
"errors.tolerance": "none",
"errors.log.enable": "true",
"errors.log.include.messages": "false"
}
}
Reference: Debezium — MongoDB sink configuration
The host name mongo is the MongoDB service as the Connect container sees it; replace it with your deployment. Add
the replicaSet option when the target is a replica set, as in the official connection string example.
curl -s -X POST -H "Content-Type: application/json" \
--data @bookshop-mongo-reviews-sink.json http://localhost:8083/connectors
curl -s http://localhost:8083/connectors/bookshop-mongo-reviews-sink/status | jq '.tasks[].state'
docker compose exec mongo mongosh -u bookshop_sync -p change-me --authenticationDatabase admin \
--quiet --eval 'db.getSiblingDB("bookshop").book_review.find().limit(1)'
A written document looks like this (values abbreviated):
book_review row{
"_id": { "id": "{\"$oid\": \"6af189a0c788084b3fbe7dcc\"}" },
"id": "{\"$oid\": \"6af189a0c788084b3fbe7dcc\"}",
"book_id": 1001,
"customer_legacy_id": 501,
"rating": 5,
"title": "A classic",
"body": "Read it twice.",
"helpful_votes": 12,
"created_at": "2019-03-14T10:15:00Z",
"document_json": "{\"_id\": {\"$oid\": \"6af189a0c788084b3fbe7dcc\"}, \"bookId\": 1001, \"tags\": [\"classic\", \"gift\"]}"
}
Reference: Debezium — MongoDB sink architecture
To verify the copy, compare counts and a few sampled documents with the table, and after a delete in PostgreSQL check
that the document with that _id is gone. Verification &
Reconciliation describes systematic checks.
Writing back to the legacy reviews collection
The example writes to a new collection, book_review, not to the legacy reviews collection, on purpose. The sink
cannot reproduce the legacy documents:
-
Their
_idis the originalObjectId; the sink writes an embedded document that holds the extended JSON of thatObjectIdas a string ({ "id": "{\"$oid\": ...}" }). Writing intoreviewswould create a second document for every review instead of updating the original one. -
Their shape is the legacy one (camel-case field names, arrays such as
tags,ISODatedates); the sink writes the flat PostgreSQL row, withcreated_atas a string anddocument_jsonas JSON text. -
The legacy
bookshop-mongo-sourceconnector would capture the sink’s writes and send them forward again, which is the replication loop described in Cut-over & Reverse Replication.
So there are two options. Either the legacy application reads the new book_review collection (often acceptable for
read-only legacy screens during the rollback window), or a small consumer translates each event into a legacy
reviews document, parsing id (or document_json) to rebuild the ObjectId and the original fields, and using a
marker field to break the loop. The second option
is the anti-corruption layer in reverse, and it uses the techniques of
Listening to Events in Applications.
Bookshop: a MongoDB catalogue from the legacy BOOK table
The second example builds a read model while the legacy system is still the owner of the data. The
bookshop-mongo-catalogue-sink connector reads the legacy.BOOKSHOP.BOOK topic of the bookshop-oracle-source
connector and keeps the books collection of a catalogue database current:
bookshop-mongo-catalogue-sink.json: legacy Oracle BOOK into a MongoDB catalogue{
"name": "bookshop-mongo-catalogue-sink",
"config": {
"connector.class": "io.debezium.connector.mongodb.MongoDbSinkConnector",
"tasks.max": "1",
"topics": "legacy.BOOKSHOP.BOOK",
"mongodb.connection.string": "mongodb://bookshop_sync:change-me@mongo:27017/?authSource=admin",
"sink.database": "catalogue",
"collection.name.format": "books",
"field.exclude.list": "legacy.BOOKSHOP.BOOK:SUPPLIER_ID,legacy.BOOKSHOP.BOOK:LAST_UPD",
"batch.size": "2048"
}
}
Reference: Debezium — MongoDB sink configuration
Each document gets { "_id": { "BOOK_ID": "1001" } }, the upper-case Oracle column names, every NUMBER column as a
string ("PRICE": "24.50", because the Bookshop source uses decimal.handling.mode=string; with the precise default
PRICE would be a Decimal128 and BOOK_ID a 64-bit integer), and PUBLISHED as milliseconds since the epoch unless
the source uses time.precision.mode=connect. A catalogue that needs numeric prices converts them in a consumer, or
reads from a dedicated source connector with different settings. The
field.exclude.list entries keep the supplier and the technical timestamp out of the public catalogue.
What the sink cannot do here is join: the catalogue document has AUTHOR_ID, not the author’s name, because each
event describes one row of one table. When the read model needs data from several tables (a book with its authors,
an order with its lines), build the aggregate in a consumer or with Kafka Streams first, as shown in the Debezium blog
post on DDD aggregates, and let a sink or the consumer write the result.
CloudEvents input
When the source connector writes events in CloudEvents format (with the CloudEvents converter), the sink recognises
them by their schema name, extracts the Debezium event from the data field, and applies it with the usual insert,
update and delete semantics. cloud.events.schema.name.pattern changes the pattern that identifies CloudEvents
records. Serialization & Schema Registries
explains the CloudEvents format.
What can go wrong
| Symptom | Cause | Fix |
|---|---|---|
|
The class name from the official page does not match the plug-in |
Use the class reported by |
"Value document must contain non-empty 'after' field" |
Events were flattened, or the topic is not a Debezium relational topic |
Remove |
Duplicate documents for the same row |
The record key changed (SMT or new source key), or another writer uses a different |
Keep the key stable; let only the sink write to the collection. |
Fields added in MongoDB disappear |
Updates replace the whole document |
Keep extra data in another collection, or write with a consumer that updates fields. |
Date queries do not match |
Debezium temporal types are stored as numbers or strings |
Use |
Collections named |
|
Set a literal name or a template. |
Task fails after a MongoDB outage |
The bulk write failed |
Restart the task once MongoDB is back; the replayed records are idempotent. |
References
The configuration on this page was derived from the official documentation and checked against the 3.7.1.Final connector classes; it was not run.