Debezium connector for MongoDB

Overview

MongoDB’s replication mechanism provides redundancy and high availability, and is the preferred way to run MongoDB in production. MongoDB connector captures the changes in a replica set or sharded cluster.

A MongoDB replica set consists of a set of servers that all have copies of the same data, and replication ensures that all changes made by clients to documents on the replica set’s primary are correctly applied to the other replica set’s servers, called secondaries. MongoDB replication works by having the primary record the changes in its oplog (or operation log), and then each of the secondaries reads the primary’s oplog and applies in order all of the operations to their own documents. When a new server is added to a replica set, that server first performs an snapshot of all of the databases and collections on the primary, and then reads the primary’s oplog to apply all changes that might have been made since it began the snapshot. This new server becomes a secondary (and able to handle queries) when it catches up to the tail of the primary’s oplog.

MongoDB connector supports two distinct modes of capturing the changes controlled by the capture.mode option:

  • oplog based
  • change streams based

Oplog capture mode (legacy)

The Debezium MongoDB connector uses the same replication mechanism as described above, though it does not actually become a member of the replica set. Just like MongoDB secondaries, however, the connector always reads the oplog of the replica set’s primary. And, when the connector sees a replica set for the first time, it looks at the oplog to get the last recorded transaction and then performs a snapshot of the primary’s databases and collections. When all the data is copied, the connector then starts streaming changes from the position it read earlier from the oplog. Operations in the MongoDB oplog are idempotent, so no matter how many times the operations are applied, they result in the same end state.

The disadvantage of this mode is that only insert change events will contain the full document, whereas update events only contain a representation of changed fields (i.e. unmodified fields cannot be obtained from an update event), and delete events contain no representation of the deleted document apart from its key.

This mode should be considered as the legacy one. It is not supported on MongoDB 5 and the user is strongly advised to not use it for MongoDB 4.x server.

Change Stream mode

The Debezium MongoDB connector uses a similar replication mechanism to the one described above, though it does not actually become a member of the replica set. The main difference is that the connector does not read the oplog directly, but delegates capturing and decoding the oplog to MongoDB’s Change Streams feature. With change streams, the MongoDB server exposes changes to collections as an event stream. The Debezium connector watches the stream and delivers the changes downstream. And, when the connector sees a replica set for the first time, it looks at the oplog to get the last recorded transaction and then performs a snapshot of the primary’s databases and collections. When all the data is copied, the connector then creates a change stream from the position it read earlier from the oplog.

This is the recommended mode starting with MongoDB 4.x and cannot be used with MongoDB 3.x.

Both capture modes use different values stored in offsets that allow them to resume streaming from the last position seen after a connector restart. Thus it is not possible to switch from the change streams mode to the oplog mode. To prevent any inadvertent capture mode changes, the connector has a built-in safety check. When the connector is started it checks the stored offsets. If the original capture mode was oplog-based and the new mode is change streams based, then it will try to migrate to change streams. If the original capture mode was change streams based, it will keep using change streams, also if the new mode is oplog-based, and a warning about this will be emitted to the logs.

As the MongoDB connector processes changes, it periodically records the position in the oplog/stream where the event originated. When the connector stops, it records the last oplog/stream position that it processed, so that upon restart it simply begins streaming from that position. In other words, the connector can be stopped, upgraded or maintained, and restarted some time later, and it will pick up exactly where it left off without losing a single event. Of course, MongoDB’s oplogs are usually capped at a maximum size, which means that the connector should not be stopped for too long, or else some of the operations in the oplog might be purged before the connector has a chance to read them. In this case, upon restart the connector will detect the missing oplog operations, perform a snapshot, and then proceed with streaming the changes.

The MongoDB connector is also quite tolerant of changes in membership and leadership of the replica sets, of additions or removals of shards within a sharded cluster, and network problems that might cause communication failures. The connector always uses the replica set’s primary node to stream changes, so when the replica set undergoes an election and a different node becomes primary, the connector will immediately stop streaming changes, connect to the new primary, and start streaming changes using the new primary node. Likewise, if connector experiences any problems communicating with the replica set primary, it will try to reconnect (using exponential backoff so as to not overwhelm the network or replica set) and continue streaming changes from where it last left off. In this way the connector is able to dynamically adjust to changes in replica set membership and to automatically handle communication failures.

Additional resources

How the MongoDB connector works

An overview of the MongoDB topologies that the connector supports is useful for planning your application.

When a MongoDB connector is configured and deployed, it starts by connecting to the MongoDB servers at the seed addresses, and determines the details about each of the available replica sets. Since each replica set has its own independent oplog, the connector will try to use a separate task for each replica set. The connector can limit the maximum number of tasks it will use, and if not enough tasks are available the connector will assign multiple replica sets to each task, although the task will still use a separate thread for each replica set.

When running the connector against a sharded cluster, use a value of tasks.max that is greater than the number of replica sets. This will allow the connector to create one task for each replica set, and will let Kafka Connect coordinate, distribute, and manage the tasks across all of the available worker processes.

Supported MongoDB topologies

The MongoDB connector supports the following MongoDB topologies:

MongoDB replica set

The Debezium MongoDB connector can capture changes from a single MongoDB replica set. Production replica sets require a minimum of at least three members.

To use the MongoDB connector with a replica set, provide the addresses of one or more replica set servers as seed addresses through the connector’s mongodb.hosts property. The connector will use these seeds to connect to the replica set, and then once connected will get from the replica set the complete set of members and which member is primary. The connector will start a task to connect to the primary and capture the changes from the primary’s oplog. When the replica set elects a new primary, the task will automatically switch over to the new primary.

When MongoDB is fronted by a proxy (such as with Docker on OS X or Windows), then when a client connects to the replica set and discovers the members, the MongoDB client will exclude the proxy as a valid member and will attempt and fail to connect directly to the members rather than go through the proxy. In such a case, set the connector’s optional mongodb.members.auto.discover configuration property to false to instruct the connector to forgo membership discovery and instead simply use the first seed address (specified via the mongodb.hosts property) as the primary node. This may work, but still make cause issues when election occurs.

MongoDB sharded cluster

A MongoDB sharded cluster consists of:

  • One or more shards, each deployed as a replica set;
  • A separate replica set that acts as the cluster’s configuration server
  • One or more routers (also called mongos) to which clients connect and that routes requests to the appropriate shards

To use the MongoDB connector with a sharded cluster, configure the connector with the host addresses of the configuration server replica set. When the connector connects to this replica set, it discovers that it is acting as the configuration server for a sharded cluster, discovers the information about each replica set used as a shard in the cluster, and will then start up a separate task to capture the changes from each replica set. If new shards are added to the cluster or existing shards removed, the connector will automatically adjust its tasks accordingly.

MongoDB standalone server

The MongoDB connector is not capable of monitoring the changes of a standalone MongoDB server, since standalone servers do not have an oplog. The connector will work if the standalone server is converted to a replica set with one member.

MongoDB does not recommend running a standalone server in production. For more information, see the MongoDB documentation.

Logical connector name

The connector configuration property mongodb.name serves as a logical name for the MongoDB replica set or sharded cluster. The connector uses the logical name in a number of ways: as the prefix for all topic names, and as a unique identifier when recording the oplog/change stream position of each replica set.

You should give each MongoDB connector a unique logical name that meaningfully describes the source MongoDB system. We recommend logical names begin with an alphabetic or underscore character, and remaining characters that are alphanumeric or underscore.

Performing a snapshot

When a task starts up using a replica set, it uses the connector’s logical name and the replica set name to find an offset that describes the position where the connector previously stopped reading changes. If an offset can be found and it still exists in the oplog, then the task immediately proceeds with streaming changes, starting at the recorded offset position.

However, if no offset is found or if the oplog no longer contains that position, the task must first obtain the current state of the replica set contents by performing a snapshot. This process starts by recording the current position of the oplog and recording that as the offset (along with a flag that denotes a snapshot has been started). The task will then proceed to copy each collection, spawning as many threads as possible (up to the value of the snapshot.max.threads configuration property) to perform this work in parallel. The connector will record a separate read event for each document it sees, and that read event will contain the object’s identifier, the complete state of the object, and source information about the MongoDB replica set where the object was found. The source information will also include a flag that denotes the event was produced during a snapshot.

This snapshot will continue until it has copied all collections that match the connector’s filters. If the connector is stopped before the tasks’ snapshots are completed, upon restart the connector begins the snapshot again.

Try to avoid task reassignment and reconfiguration while the connector performs snapshots of any replica sets. The connector generates log messages to report on the progress of the snapshot. To provide for the greatest control, run a separate Kafka Connect cluster for each connector.

Ad hoc snapshots

By default, a connector runs an initial snapshot operation only after it starts for the first time. Following this initial snapshot, under normal circumstances, the connector does not repeat the snapshot process. Any future change event data that the connector captures comes in through the streaming process only.

However, in some situations the data that the connector obtained during the initial snapshot might become stale, lost, or incomplete. To provide a mechanism for recapturing collection data, Debezium includes an option to perform ad hoc snapshots. The following changes in a database might be cause for performing an ad hoc snapshot:

  • The connector configuration is modified to capture a different set of collections.
  • Kafka topics are deleted and must be rebuilt.
  • Data corruption occurs due to a configuration error or some other problem.

You can re-run a snapshot for a collection for which you previously captured a snapshot by initiating a so-called ad-hoc snapshot. Ad hoc snapshots require the use of signaling collections. You initiate an ad hoc snapshot by sending a signal request to the Debezium signaling collection.

When you initiate an ad hoc snapshot of an existing collection, the connector appends content to the topic that already exists for the collection. If a previously existing topic was removed, Debezium can create a topic automatically if automatic topic creation is enabled.

Ad hoc snapshot signals specify the collections to include in the snapshot. The snapshot can capture the entire contents of the database, or capture only a subset of the collections in the database.

You specify the collections to capture by sending an execute-snapshot message to the signaling collection. Set the type of the execute-snapshot signal to incremental, and provide the names of the collections to include in the snapshot, as described in the following table:

Table 1. Example of an ad hoc execute-snapshot signal record

| Field | Default | Value |

| --- | --- | --- | | type | incremental | Specifies the type of snapshot that you want to run. Setting the type is optional. Currently, you can request only incremental snapshots. | | data-collections | N/A | An array that contains the fully-qualified names of the collection to be snapshotted. The format of the names is the same as for the signal.data.collection configuration option. |

Triggering an ad hoc snapshot

You initiate an ad hoc snapshot by adding an entry with the execute-snapshot signal type to the signaling collection. After the connector processes the message, it begins the snapshot operation. The snapshot process reads the first and last primary key values and uses those values as the start and end point for each collection. Based on the number of entries in the collection, and the configured chunk size, Debezium divides the collection into chunks, and proceeds to snapshot each chunk, in succession, one at a time.

Currently, the execute-snapshot action type triggers incremental snapshots only. For more information, see Incremental snapshots.

Incremental snapshots

To provide flexibility in managing snapshots, Debezium includes a supplementary snapshot mechanism, known as incremental snapshotting. Incremental snapshots rely on the Debezium mechanism for sending signals to a Debezium connector. Incremental snapshots are based on the DDD-3 design document.

In an incremental snapshot, instead of capturing the full state of a database all at once, as in an initial snapshot, Debezium captures each collection in phases, in a series of configurable chunks. You can specify the collections that you want the snapshot to capture and the size of each chunk. The chunk size determines the number of rows that the snapshot collects during each fetch operation on the database. The default chunk size for incremental snapshots is 1 KB.

As an incremental snapshot proceeds, Debezium uses watermarks to track its progress, maintaining a record of each collection row that it captures. This phased approach to capturing data provides the following advantages over the standard initial snapshot process:

  • You can run incremental snapshots in parallel with streamed data capture, instead of postponing streaming until the snapshot completes. The connector continues to capture near real-time events from the change log throughout the snapshot process, and neither operation blocks the other.
  • If the progress of an incremental snapshot is interrupted, you can resume it without losing any data. After the process resumes, the snapshot begins at the point where it stopped, rather than recapturing the collection from the beginning.
  • You can run an incremental snapshot on demand at any time, and repeat the process as needed to adapt to database updates. For example, you might re-run a snapshot after you modify the connector configuration to add a collection to its collection.include.list property.

Incremental snapshot process

When you run an incremental snapshot, Debezium sorts each collection by primary key and then splits the collection into chunks based on the configured chunk size. Working chunk by chunk, it then captures each collection row in a chunk. For each row that it captures, the snapshot emits a READ event. That event represents the value of the row when the snapshot for the chunk began.

As a snapshot proceeds, it’s likely that other processes continue to access the database, potentially modifying collection records. To reflect such changes, INSERT, UPDATE, or DELETE operations are committed to the transaction log as per usual. Similarly, the ongoing Debezium streaming process continues to detect these change events and emits corresponding change event records to Kafka.

How Debezium resolves collisions among records with the same primary key

In some cases, the UPDATE or DELETE events that the streaming process emits are received out of sequence. That is, the streaming process might emit an event that modifies a collection row before the snapshot captures the chunk that contains the READ event for that row. When the snapshot eventually emits the corresponding READ event for the row, its value is already superseded. To ensure that incremental snapshot events that arrive out of sequence are processed in the correct logical order, Debezium employs a buffering scheme for resolving collisions. Only after collisions between the snapshot events and the streamed events are resolved does Debezium emit an event record to Kafka.

Snapshot window

To assist in resolving collisions between late-arriving READ events and streamed events that modify the same collection row, Debezium employs a so-called snapshot window. The snapshot windows demarcates the interval during which an incremental snapshot captures data for a specified collection chunk. Before the snapshot window for a chunk opens, Debezium follows its usual behavior and emits events from the transaction log directly downstream to the target Kafka topic. But from the moment that the snapshot for a particular chunk opens, until it closes, Debezium performs a de-duplication step to resolve collisions between events that have the same primary key..

For each data collection, the Debezium emits two types of events, and stores the records for them both in a single destination Kafka topic. The snapshot records that it captures directly from a table are emitted as READ operations. Meanwhile, as users continue to update records in the data collection, and the transaction log is updated to reflect each commit, Debezium emits UPDATE or DELETE operations for each change.

As the snapshot window opens, and Debezium begins processing a snapshot chunk, it delivers snapshot records to a memory buffer. During the snapshot windows, the primary keys of the READ events in the buffer are compared to the primary keys of the incoming streamed events. If no match is found, the streamed event record is sent directly to Kafka. If Debezium detects a match, it discards the buffered READ event, and writes the streamed record to the destination topic, because the streamed event logically supersede the static snapshot event. After the snapshot window for the chunk closes, the buffer contains only READ events for which no related transaction log events exist. Debezium emits these remaining READ events to the collection’s Kafka topic.

The connector repeats the process for each snapshot chunk.

Triggering an incremental snapshot

Currently, the only way to initiate an incremental snapshot is to send an ad hoc snapshot signal to the signaling collection on the source database. You submit signals to the collection as SQL INSERT queries. After Debezium detects the change in the signaling collection, it reads the signal, and runs the requested snapshot operation.

The query that you submit specifies the collections to include in the snapshot, and, optionally, specifies the kind of snapshot operation. Currently, the only valid option for snapshots operations is the default value, incremental.

To specify the collections to include in the snapshot, provide a data-collections array that lists the collections, for example, {"data-collections": ["public.MyFirstTable", "public.MySecondTable"]}

The data-collections array for an incremental snapshot signal has no default value. If the data-collections array is empty, Debezium detects that no action is required and does not perform a snapshot.

If the name of a collection that you want to include in a snapshot contains a dot (.) in the name of the database, schema, or table, to add the collection to the data-collections array, you must escape each part of the name in double quotes. For example, to include a table that exists in the public schema and that has the name My.Table, use the following format: “public”.”My.Table”.

Prerequisites

  • Signaling is enabled.

  • A signaling data collection exists on the source database and the connector is configured to capture it.

  • The signaling data collection is specified in the signal.data.collection property.

Procedure

  1. Send a SQL query to add the ad hoc incremental snapshot request to the signaling collection:

1. INSERT INTO _<signalTable>_ (id, type, data) VALUES (_'<id>'_, _'<snapshotType>'_, '{"data-collections": ["_<tableName>_","_<tableName>_"],"type":"_<snapshotType>_"}');

For example,

1. INSERT INTO myschema.debezium_signal (id, type, data) VALUES('ad-hoc-1', 'execute-snapshot', '{"data-collections": ["schema1.table1", "schema2.table2"],"type":"incremental"}');

The values of the id,type, and data parameters in the command correspond to the fields of the signaling collection.

The following collection describes the these parameters:

Table 2. Descriptions of fields in a SQL command for sending an incremental snapshot signal to the signaling collection

  | Value | Description |

| --- | --- | | myschema.debezium_signal | Specifies the fully-qualified name of the signaling collection on the source database | | ad-hoc-1 | The id parameter specifies an arbitrary string that is assigned as the id identifier for the signal request. Use this string to identify logging messages to entries in the signaling collection. Debezium does not use this string. Rather, during the snapshot, Debezium generates its own id string as a watermarking signal. | | execute-snapshot | Specifies type parameter specifies the operation that the signal is intended to trigger. | | data-collections | A required component of the data field of a signal that specifies an array of collection names to include in the snapshot. The array lists collections by their fully-qualified names, using the same format as you use to specify the name of the connector’s signaling collection in the signal.data.collection configuration property. | | incremental | An optional type component of the data field of a signal that specifies the kind of snapshot operation to run. Currently, the only valid option is the default value, incremental. Specifying a type value in the SQL query that you submit to the signaling collection is optional. If you do not specify a value, the connector runs an incremental snapshot. |

The following example, shows the JSON for an incremental snapshot event that is captured by a connector.

Example: Incremental snapshot event message

1. {
2. "before":null,
3. "after": {
4. "pk":"1",
5. "value":"New data"
6. },
7. "source": {
8. ...
9. "snapshot":"incremental" (1)
10. },
11. "op":"r", (2)
12. "ts_ms":"1620393591654",
13. "transaction":null
14. }
Item Field name Description
1 snapshot Specifies the type of snapshot operation to run. Currently, the only valid option is the default value, incremental. Specifying a type value in the SQL query that you submit to the signaling collection is optional. If you do not specify a value, the connector runs an incremental snapshot.
2 op Specifies the event type. The value for snapshot events is r, signifying a READ operation.
Incremental snapshots are currently supported for single replica set deployments only. This limitation will be removed in the next version.

Streaming changes

After the connector task for a replica set records an offset, it uses the offset to determine the position in the oplog where it should start streaming changes. The task then (depending on the configuration) either connects to the replica set’s primary node or connects to a replica-set-wide change stream and starts streaming changes from that position. It processes all of create, insert, and delete operations, and converts them into Debezium change events. Each change event includes the position in the oplog where the operation was found, and the connector periodically records this as its most recent offset. The interval at which the offset is recorded is governed by offset.flush.interval.ms, which is a Kafka Connect worker configuration property.

When the connector is stopped gracefully, the last offset processed is recorded so that, upon restart, the connector will continue exactly where it left off. If the connector’s tasks terminate unexpectedly, however, then the tasks may have processed and generated events after it last records the offset but before the last offset is recorded; upon restart, the connector begins at the last recorded offset, possibly generating some the same events that were previously generated just prior to the crash.

When everything is operating nominally, Kafka consumers will actually see every message exactly once. However, when things go wrong Kafka can only guarantee consumers will see every message at least once. Therefore, your consumers need to anticipate seeing messages more than once.

As mentioned above, the connector tasks always use the replica set’s primary node to stream changes from the oplog, ensuring that the connector sees the most up-to-date operations as possible and can capture the changes with lower latency than if secondaries were to be used instead. When the replica set elects a new primary, the connector immediately stops streaming changes, connects to the new primary, and starts streaming changes from the new primary node at the same position. Likewise, if the connector experiences any problems communicating with the replica set members, it tries to reconnect, by using exponential backoff so as to not overwhelm the replica set, and once connected it continues streaming changes from where it last left off. In this way, the connector is able to dynamically adjust to changes in replica set membership and automatically handle communication failures.

To summarize, the MongoDB connector continues running in most situations. Communication problems might cause the connector to wait until the problems are resolved.

Topic names

The MongoDB connector writes events for all insert, update, and delete operations to documents in each collection to a single Kafka topic. The name of the Kafka topics always takes the form logicalName.databaseName.collectionName, where logicalName is the logical name of the connector as specified with the mongodb.name configuration property, databaseName is the name of the database where the operation occurred, and collectionName is the name of the MongoDB collection in which the affected document existed.

For example, consider a MongoDB replica set with an inventory database that contains four collections: products, products_on_hand, customers, and orders. If the connector monitoring this database were given a logical name of fulfillment, then the connector would produce events on these four Kafka topics:

  • fulfillment.inventory.products
  • fulfillment.inventory.products_on_hand
  • fulfillment.inventory.customers
  • fulfillment.inventory.orders

Notice that the topic names do not incorporate the replica set name or shard name. As a result, all changes to a sharded collection (where each shard contains a subset of the collection’s documents) all go to the same Kafka topic.

You can set up Kafka to auto-create the topics as they are needed. If not, then you must use Kafka administration tools to create the topics before starting the connector.

Partitions

The MongoDB connector does not make any explicit determination about how to partition topics for events. Instead, it allows Kafka to determine how to partition topics based on event keys. You can change Kafka’s partitioning logic by defining the name of the Partitioner implementation in the Kafka Connect worker configuration.

Kafka maintains total order only for events written to a single topic partition. Partitioning the events by key does mean that all events with the same key always go to the same partition. This ensures that all events for a specific document are always totally ordered.

Transaction Metadata

Debezium can generate events that represents transaction metadata boundaries and enrich change data event messages.

Limits on when Debezium receives transaction metadata Debezium registers and receives metadata only for transactions that occur after you deploy the connector. Metadata for transactions that occur before you deploy the connector is not available.

For every transaction BEGIN and END, Debezium generates an event that contains the following fields:

status

BEGIN or END

id

String representation of unique transaction identifier.

event_count (for END events)

Total number of events emitted by the transaction.

data_collections (for END events)

An array of pairs of data_collection and event_count that provides number of events emitted by changes originating from given data collection.

The following example shows a typical message:

1. {
2. "status": "BEGIN",
3. "id": "1462833718356672513",
4. "event_count": null,
5. "data_collections": null
6. }

8. {
9. "status": "END",
10. "id": "1462833718356672513",
11. "event_count": 2,
12. "data_collections": [
13. {
14. "data_collection": "rs0.testDB.collectiona",
15. "event_count": 1
16. },
17. {
18. "data_collection": "rs0.testDB.collectionb",
19. "event_count": 1
20. }
21. ]
22. }

Unless overridden via the transaction.topic option, transaction events are written to the topic named *database.server.name*.transaction.

Change data event enrichment

When transaction metadata is enabled, the data message Envelope is enriched with a new transaction field. This field provides information about every event in the form of a composite of fields:

id

String representation of unique transaction identifier.

total_order

The absolute position of the event among all events generated by the transaction.

data_collection_order

The per-data collection position of the event among all events that were emitted by the transaction.

Following is an example of what a message looks like:

1. {
2. "patch": null,
3. "after": "{\"_id\" : {\"$numberLong\" : \"1004\"},\"first_name\" : \"Anne\",\"last_name\" : \"Kretchmar\",\"email\" : \"annek@noanswer.org\"}",
4. "source": {
5. ...
6. },
7. "op": "c",
8. "ts_ms": "1580390884335",
9. "transaction": {
10. "id": "1462833718356672513",
11. "total_order": "1",
12. "data_collection_order": "1"
13. }
14. }

Data change events

The Debezium MongoDB connector generates a data change event for each document-level operation that inserts, updates, or deletes data. Each event contains a key and a value. The structure of the key and the value depends on the collection that was changed.

Debezium and Kafka Connect are designed around continuous streams of event messages. However, the structure of these events may change over time, which can be difficult for consumers to handle. To address this, each event contains the schema for its content or, if you are using a schema registry, a schema ID that a consumer can use to obtain the schema from the registry. This makes each event self-contained.

The following skeleton JSON shows the basic four parts of a change event. However, how you configure the Kafka Connect converter that you choose to use in your application determines the representation of these four parts in change events. A schema field is in a change event only when you configure the converter to produce it. Likewise, the event key and event payload are in a change event only if you configure a converter to produce it. If you use the JSON converter and you configure it to produce all four basic change event parts, change events have this structure:

1. {
2. "schema": { (1)
3. ...
4. },
5. "payload": { (2)
6. ...
7. },
8. "schema": { (3)
9. ...
10. },
11. "payload": { (4)
12. ...
13. },
14. }

Table 3. Overview of change event basic content

| Item | Field name | Description |

| --- | --- | --- | | 1 | schema | The first schema field is part of the event key. It specifies a Kafka Connect schema that describes what is in the event key’s payload portion. In other words, the first schema field describes the structure of the key for the document that was changed. | | 2 | payload | The first payload field is part of the event key. It has the structure described by the previous schema field and it contains the key for the document that was changed. | | 3 | schema | The second schema field is part of the event value. It specifies the Kafka Connect schema that describes what is in the event value’s payload portion. In other words, the second schema describes the structure of the document that was changed. Typically, this schema contains nested schemas. | | 4 | payload | The second payload field is part of the event value. It has the structure described by the previous schema field and it contains the actual data for the document that was changed. |

By default, the connector streams change event records to topics with names that are the same as the event’s originating collection. See topic names.

The MongoDB connector ensures that all Kafka Connect schema names adhere to the Avro schema name format. This means that the logical server name must start with a Latin letter or an underscore, that is, a-z, A-Z, or *. Each remaining character in the logical server name and each character in the database and collection names must be a Latin letter, a digit, or an underscore, that is, a-z, A-Z, 0-9, or *. If there is an invalid character it is replaced with an underscore character. This can lead to unexpected conflicts if the logical server name, a database name, or a collection name contains invalid characters, and the only characters that distinguish names from one another are invalid and thus replaced with underscores.

Change event keys

A change event’s key contains the schema for the changed document’s key and the changed document’s actual key. For a given collection, both the schema and its corresponding payload contain a single id field. The value of this field is the document’s identifier represented as a string that is derived from MongoDB extended JSON serialization strict mode.

Consider a connector with a logical name of fulfillment, a replica set containing an inventory database, and a customers collection that contains documents such as the following.

Example document

1. {
2. "_id": 1004,
3. "first_name": "Anne",
4. "last_name": "Kretchmar",
5. "email": "annek@noanswer.org"
6. }

Example change event key

Every change event that captures a change to the customers collection has the same event key schema. For as long as the customers collection has the previous definition, every change event that captures a change to the customers collection has the following key structure. In JSON, it looks like this:

1. {
2. "schema": { (1)
3. "type": "struct",
4. "name": "fulfillment.inventory.customers.Key", (2)
5. "optional": false, (3)
6. "fields": [ (4)
7. {
8. "field": "id",
9. "type": "string",
10. "optional": false
11. }
12. ]
13. },
14. "payload": { (5)
15. "id": "1004"
16. }
17. }

Table 4. Description of change event key

| Item | Field name | Description |

| --- | --- | --- | | 1 | schema | The schema portion of the key specifies a Kafka Connect schema that describes what is in the key’s payload portion. | | 2 | fulfillment.inventory.customers.Key | Name of the schema that defines the structure of the key’s payload. This schema describes the structure of the key for the document that was changed. Key schema names have the format connector-name.database-name.collection-name.Key. In this example: - fulfillment is the name of the connector that generated this event. - inventory is the database that contains the collection that was changed. - customers is the collection that contains the document that was updated. | | 3 | optional | Indicates whether the event key must contain a value in its payload field. In this example, a value in the key’s payload is required. A value in the key’s payload field is optional when a document does not have a key. | | 4 | fields | Specifies each field that is expected in the payload, including each field’s name, type, and whether it is required. | | 5 | payload | Contains the key for the document for which this change event was generated. In this example, the key contains a single id field of type string whose value is 1004. |

This example uses a document with an integer identifier, but any valid MongoDB document identifier works the same way, including a document identifier. For a document identifier, an event key’s payload.id value is a string that represents the updated document’s original _id field as a MongoDB extended JSON serialization that uses strict mode. The following table provides examples of how different types of _id fields are represented.

Table 5. Examples of representing document _id fields in event key payloads

| Type | MongoDB `_id` Value | Key’s payload |

| --- | --- | --- | | Integer | 1234 | { “id” : “1234” } | | Float | 12.34 | { “id” : “12.34” } | | String | “1234” | { “id” : “\”1234\”” } | | Document | { “hi” : “kafka”, “nums” : [10.0, 100.0, 1000.0] } | { “id” : “{\”hi\” : \”kafka\”, \”nums\” : [10.0, 100.0, 1000.0]}” } | | ObjectId | ObjectId(“596e275826f08b2730779e1f”) | { “id” : “{\”$oid\” : \”596e275826f08b2730779e1f\”}” } | | Binary | BinData(“a2Fma2E=”,0) | { “id” : “{\”$binary\” : \”a2Fma2E=\”, \”$type\” : \”00\”}” } |

Change event values

The value in a change event is a bit more complicated than the key. Like the key, the value has a schema section and a payload section. The schema section contains the schema that describes the Envelope structure of the payload section, including its nested fields. Change events for operations that create, update or delete data all have a value payload with an envelope structure.

Consider the same sample document that was used to show an example of a change event key:

Example document

1. {
2. "_id": 1004,
3. "first_name": "Anne",
4. "last_name": "Kretchmar",
5. "email": "annek@noanswer.org"
6. }

The value portion of a change event for a change to this document is described for each event type:

create events

The following example shows the value portion of a change event that the connector generates for an operation that creates data in the customers collection:

``` 1. { 2. "schema": { (1) 3. "type": "struct", 4. "fields": [ 5. { 6. "type": "string", 7. "optional": true, 8. "name": "io.debezium.data.Json", (2) 9. "version": 1, 10. "field": "after" 11. }, 12. { 13. "type": "string", 14. "optional": true, 15. "name": "io.debezium.data.Json", 16. "version": 1, 17. "field": "patch" 18. }, 19. { 20. "type": "struct", 21. "fields": [ 22. { 23. "type": "string", 24. "optional": false, 25. "field": "version" 26. }, 27. { 28. "type": "string", 29. "optional": false, 30. "field": "connector" 31. }, 32. { 33. "type": "string", 34. "optional": false, 35. "field": "name" 36. }, 37. { 38. "type": "int64", 39. "optional": false, 40. "field": "ts_ms" 41. }, 42. { 43. "type": "boolean", 44. "optional": true, 45. "default": false, 46. "field": "snapshot" 47. }, 48. { 49. "type": "string", 50. "optional": false, 51. "field": "db" 52. }, 53. { 54. "type": "string", 55. "optional": false, 56. "field": "rs" 57. }, 58. { 59. "type": "string", 60. "optional": false, 61. "field": "collection" 62. }, 63. { 64. "type": "int32", 65. "optional": false, 66. "field": "ord" 67. }, 68. { 69. "type": "int64", 70. "optional": true, 71. "field": "h" 72. } 73. ], 74. "optional": false, 75. "name": "io.debezium.connector.mongo.Source", (3) 76. "field": "source" 77. }, 78. { 79. "type": "string", 80. "optional": true, 81. "field": "op" 82. }, 83. { 84. "type": "int64", 85. "optional": true, 86. "field": "ts_ms" 87. } 8

(本文超出站点单文档体积上限,已截断)