You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@seatunnel.apache.org by gi...@apache.org on 2026/09/11 04:49:50 UTC

(seatunnel) branch dev updated: [Feature][Connector-V2][MongoDB-CDC] Support timestamp stop mode (#11815)

This is an automated email from the ASF dual-hosted git repository.

github-merge-queue[bot] pushed a commit to branch dev
in repository https://gitbox.apache.org/repos/asf/seatunnel.git


The following commit(s) were added to refs/heads/dev by this push:
     new cc387508c9 [Feature][Connector-V2][MongoDB-CDC] Support timestamp stop mode (#11815)
cc387508c9 is described below

commit cc387508c992391ba2d14ac7316fc33d2cfebe5f
Author: Goutam Adwant <86...@users.noreply.github.com>
AuthorDate: Fri Sep 11 04:40:33 2026 +0000

    [Feature][Connector-V2][MongoDB-CDC] Support timestamp stop mode (#11815)
    
    Signed-off-by: goutamadwant <wo...@gmail.com>
---
 docs/en/connectors/source/MongoDB-CDC.md           |  42 +++++++
 docs/zh/connectors/source/MongoDB-CDC.md           |  42 +++++++
 .../connectors/cdc/base/config/StopConfig.java     |   2 +-
 .../cdc/mongodb/MongodbIncrementalSource.java      |   5 +-
 .../mongodb/MongodbIncrementalSourceFactory.java   |   6 +
 .../config/MongodbIncrementalSourceOptions.java    |   9 +-
 .../config/MongodbSourceConfigProvider.java        |  28 ++++-
 .../source/fetch/MongodbStreamFetchTask.java       |  13 ++-
 .../MongodbIncrementalSourceFactoryTest.java       | 125 +++++++++++++++++++++
 .../source/fetch/MongodbStreamFetchTaskTest.java   |  37 ++++++
 .../src/test/java/mongodb/MongodbCDCIT.java        | 120 ++++++++++++++++++++
 .../resources/mongodbcdc_stop_mode_timestamp.conf  |  61 ++++++++++
 12 files changed, 479 insertions(+), 11 deletions(-)

diff --git a/docs/en/connectors/source/MongoDB-CDC.md b/docs/en/connectors/source/MongoDB-CDC.md
index 401e09ca16..f22e62d7ac 100644
--- a/docs/en/connectors/source/MongoDB-CDC.md
+++ b/docs/en/connectors/source/MongoDB-CDC.md
@@ -129,6 +129,8 @@ For specific types in MongoDB, we use Extended JSON format to map them to Seatun
 | incremental.snapshot.chunk.size.mb | Integer | No       | 64      | Chunk size, in MB, for incremental snapshot reading.                                                                                                                                                                                                                     |
 | startup.mode                       | Enum    | No       | INITIAL | Optional startup mode for MongoDB CDC consumer. Valid values are `initial`, `latest`, and `timestamp`. See the [Startup Mode](#startup-mode) section below.                                                                                                               |
 | startup.timestamp                  | Long    | No       | -       | Start from the specified epoch timestamp in milliseconds. Only used when `startup.mode` is `timestamp`.                                                                                                                                                                   |
+| stop.mode                          | Enum    | No       | NEVER   | Optional stop mode for MongoDB CDC consumer. Valid values are `never` and `timestamp`. See the [Stop Mode](#stop-mode) section below.                                                                                                                                      |
+| stop.timestamp                     | Long    | No       | -       | Stop at the change-stream position derived from this epoch timestamp in milliseconds. Only used when `stop.mode` is `timestamp`.                                                                                                                                           |
 | exactly_once                       | Boolean | No       | false   | Enable exactly-once semantics. Enabling this may increase memory usage during large table snapshot recovery.                                                                                                                                                              |
 | debezium                           | Config  | No       | -       | Pass-through Debezium properties used by the embedded engine.                                                                                                                                                                                                             |
 | common-options                     |         | No       | -       | Source plugin common parameters. For details, see [Source Common Options](../common-options/source-common-options.md).                                                                                                                                                    |
@@ -164,6 +166,46 @@ source {
 }
 ```
 
+### Stop Mode
+
+The `stop.mode` option controls whether the connector runs continuously or finishes at a bounded change-stream position:
+
+- `never` (default): keeps reading the change stream.
+- `timestamp`: reads until the MongoDB change-stream timestamp reaches the position derived from `stop.timestamp`, drains the records already produced by the source, and then finishes the job.
+
+MongoDB change-stream timestamps have second precision. `stop.timestamp` is supplied as epoch milliseconds and converted to that timestamp representation. Events after the stop position are not emitted.
+
+- A timestamp startup and timestamp stop must resolve to different positions, with the stop position later than the startup position. Values within the same second resolve to the same position and are rejected.
+- Timestamp stop mode makes the source bounded, so a streaming job finishes after every split reaches the stop position.
+- With `startup.mode = initial`, the initial snapshot is read completely. The stop timestamp only bounds the incremental change-stream phase.
+- With `startup.mode = latest`, a stop position that has already passed produces no incremental records and the bounded source finishes.
+- After checkpoint or savepoint restore, the stop position stored in the restored split takes precedence over a changed `stop.timestamp` in the submitted configuration.
+- On an idle bounded stream, the connector checks MongoDB cluster time once per poll so it can finish even when no change event reaches the boundary.
+
+For example, to read a bounded interval:
+
+```hocon
+source {
+  MongoDB-CDC {
+    hosts = "mongo0:27017"
+    database = ["inventory"]
+    collection = ["inventory.products"]
+    startup.mode = "timestamp"
+    startup.timestamp = 1785542400000
+    stop.mode = "timestamp"
+    stop.timestamp = 1785546000000
+    schema = {
+      fields {
+        "_id" : string,
+        "name" : string,
+        "description" : string,
+        "weight" : string
+      }
+    }
+  }
+}
+```
+
 ### Tips
 
 > 1.If the collection changes at a slow pace, it is strongly recommended to set an appropriate value greater than 0 for the heartbeat.interval.ms parameter. When we recover a Seatunnel job from a checkpoint or savepoint, the heartbeat events can push the resumeToken forward to avoid its expiration.<br/>
diff --git a/docs/zh/connectors/source/MongoDB-CDC.md b/docs/zh/connectors/source/MongoDB-CDC.md
index 1785cfb724..7b60d22742 100644
--- a/docs/zh/connectors/source/MongoDB-CDC.md
+++ b/docs/zh/connectors/source/MongoDB-CDC.md
@@ -129,6 +129,8 @@ db.grantRolesToUser("<USER_NAME>", ["<ROLE_NAME>"])
 | incremental.snapshot.chunk.size.mb | Integer | 否   | 64      | 增量快照读取时的分片大小,单位为 MB。                                                                                       |
 | startup.mode                       | Enum    | 否   | INITIAL | MongoDB CDC 的启动模式,可选值为 `initial`、`latest` 和 `timestamp`。详见下方[启动模式](#启动模式)。                         |
 | startup.timestamp                  | Long    | 否   | -       | 从指定的毫秒级时间戳开始消费。仅在 `startup.mode` 为 `timestamp` 时使用。                                                   |
+| stop.mode                          | Enum    | 否   | NEVER   | MongoDB CDC 的停止模式,可选值为 `never` 和 `timestamp`。详见下方[停止模式](#停止模式)。                                    |
+| stop.timestamp                     | Long    | 否   | -       | 在该毫秒级时间戳对应的变更流位置停止。仅在 `stop.mode` 为 `timestamp` 时使用。                                               |
 | exactly_once                       | Boolean | 否   | false   | 启用精确一次语义。开启后,大表快照阶段恢复时可能增加内存使用。                                                              |
 | debezium                           | Config  | 否   | -       | 透传给内嵌 Debezium 引擎的配置。                                                                                            |
 | common-options                     |         | 否   | -       | 源插件通用参数,请参考 [源通用选项](../common-options/source-common-options.md)。                                             |
@@ -164,6 +166,46 @@ source {
 }
 ```
 
+### 停止模式
+
+`stop.mode` 选项控制连接器是持续运行,还是在指定的变更流位置完成作业:
+
+- `never`(默认):持续读取变更流。
+- `timestamp`:读取到 `stop.timestamp` 对应的 MongoDB 变更流时间戳,排空源已产生的记录后完成作业。
+
+MongoDB 变更流时间戳的精度为秒。`stop.timestamp` 使用毫秒级 epoch 时间戳配置,并转换为 MongoDB 的时间戳表示。停止位置之后的事件不会输出。
+
+- 当启动和停止模式都使用时间戳时,停止位置必须晚于启动位置。位于同一秒内的不同毫秒值会转换为相同位置,因此会被拒绝。
+- 时间戳停止模式会将 source 设为有界模式,所有 split 到达停止位置后,流式作业会结束。
+- 使用 `startup.mode = initial` 时,初始快照会完整读取,停止时间戳只限制增量变更流阶段。
+- 使用 `startup.mode = latest` 时,如果停止位置已经过去,增量阶段不会输出记录,有界 source 会直接结束。
+- 从 checkpoint 或 savepoint 恢复后,恢复的 split 中保存的停止位置优先于重新提交配置中修改后的 `stop.timestamp`。
+- 对于空闲的有界变更流,连接器每次轮询会检查一次 MongoDB 集群时间,使其在没有变更事件到达边界时也能结束。
+
+例如,读取一个有界时间区间:
+
+```hocon
+source {
+  MongoDB-CDC {
+    hosts = "mongo0:27017"
+    database = ["inventory"]
+    collection = ["inventory.products"]
+    startup.mode = "timestamp"
+    startup.timestamp = 1785542400000
+    stop.mode = "timestamp"
+    stop.timestamp = 1785546000000
+    schema = {
+      fields {
+        "_id" : string,
+        "name" : string,
+        "description" : string,
+        "weight" : string
+      }
+    }
+  }
+}
+```
+
 ### 提示
 
 > 1.如果集合更改速度较慢,强烈建议为heartbeat.interval.ms参数设置一个大于0的适当值。当我们从检查点或保存点恢复Seatunnel作业时,心跳事件可以向前推resumeToken以避免其过期。<br/>
diff --git a/seatunnel-connectors-v2/connector-cdc/connector-cdc-base/src/main/java/org/apache/seatunnel/connectors/cdc/base/config/StopConfig.java b/seatunnel-connectors-v2/connector-cdc/connector-cdc-base/src/main/java/org/apache/seatunnel/connectors/cdc/base/config/StopConfig.java
index 343cb95644..b6f5be519c 100644
--- a/seatunnel-connectors-v2/connector-cdc/connector-cdc-base/src/main/java/org/apache/seatunnel/connectors/cdc/base/config/StopConfig.java
+++ b/seatunnel-connectors-v2/connector-cdc/connector-cdc-base/src/main/java/org/apache/seatunnel/connectors/cdc/base/config/StopConfig.java
@@ -35,7 +35,7 @@ public final class StopConfig implements Serializable {
     @Getter private final StopMode stopMode;
     private final String specificOffsetFile;
     private final Long specificOffsetPos;
-    private final Long timestamp;
+    @Getter private final Long timestamp;
 
     public Offset getStopOffset(OffsetFactory offsetFactory) {
         switch (stopMode) {
diff --git a/seatunnel-connectors-v2/connector-cdc/connector-cdc-mongodb/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/mongodb/MongodbIncrementalSource.java b/seatunnel-connectors-v2/connector-cdc/connector-cdc-mongodb/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/mongodb/MongodbIncrementalSource.java
index 2c95075f49..f6bac02982 100644
--- a/seatunnel-connectors-v2/connector-cdc/connector-cdc-mongodb/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/mongodb/MongodbIncrementalSource.java
+++ b/seatunnel-connectors-v2/connector-cdc/connector-cdc-mongodb/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/mongodb/MongodbIncrementalSource.java
@@ -77,8 +77,7 @@ public class MongodbIncrementalSource<T> extends IncrementalSource<T, MongodbSou
             @Nonnull ReadonlyConfig config) {
         MongodbSourceConfigProvider.Builder builder =
                 MongodbSourceConfigProvider.newBuilder()
-                        .hosts(config.get(MongodbIncrementalSourceOptions.HOSTS))
-                        .validate();
+                        .hosts(config.get(MongodbIncrementalSourceOptions.HOSTS));
         Optional.ofNullable(config.get(MongodbIncrementalSourceOptions.DATABASE))
                 .ifPresent(builder::databaseList);
         Optional.ofNullable(config.get(MongodbIncrementalSourceOptions.COLLECTION))
@@ -105,7 +104,7 @@ public class MongodbIncrementalSource<T> extends IncrementalSource<T, MongodbSou
                 .ifPresent(builder::splitSizeMB);
         Optional.ofNullable(startupConfig).ifPresent(builder::startupOptions);
         Optional.ofNullable(stopConfig).ifPresent(builder::stopOptions);
-        return builder;
+        return builder.validate();
     }
 
     @SuppressWarnings("unchecked")
diff --git a/seatunnel-connectors-v2/connector-cdc/connector-cdc-mongodb/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/mongodb/MongodbIncrementalSourceFactory.java b/seatunnel-connectors-v2/connector-cdc/connector-cdc-mongodb/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/mongodb/MongodbIncrementalSourceFactory.java
index bee67a5334..1aeb1e9071 100644
--- a/seatunnel-connectors-v2/connector-cdc/connector-cdc-mongodb/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/mongodb/MongodbIncrementalSourceFactory.java
+++ b/seatunnel-connectors-v2/connector-cdc/connector-cdc-mongodb/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/mongodb/MongodbIncrementalSourceFactory.java
@@ -31,7 +31,9 @@ import org.apache.seatunnel.api.table.factory.Factory;
 import org.apache.seatunnel.api.table.factory.TableSourceFactory;
 import org.apache.seatunnel.api.table.factory.TableSourceFactoryContext;
 import org.apache.seatunnel.common.utils.SeaTunnelException;
+import org.apache.seatunnel.connectors.cdc.base.option.SourceOptions;
 import org.apache.seatunnel.connectors.cdc.base.option.StartupMode;
+import org.apache.seatunnel.connectors.cdc.base.option.StopMode;
 import org.apache.seatunnel.connectors.seatunnel.cdc.mongodb.config.MongodbIncrementalSourceOptions;
 import org.apache.seatunnel.connectors.seatunnel.cdc.mongodb.exception.MongodbConnectorException;
 
@@ -78,6 +80,10 @@ public class MongodbIncrementalSourceFactory implements TableSourceFactory {
                         MongodbIncrementalSourceOptions.STARTUP_MODE,
                         StartupMode.TIMESTAMP,
                         MongodbIncrementalSourceOptions.STARTUP_TIMESTAMP)
+                .conditional(
+                        MongodbIncrementalSourceOptions.STOP_MODE,
+                        StopMode.TIMESTAMP,
+                        SourceOptions.STOP_TIMESTAMP)
                 .build();
     }
 
diff --git a/seatunnel-connectors-v2/connector-cdc/connector-cdc-mongodb/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/mongodb/config/MongodbIncrementalSourceOptions.java b/seatunnel-connectors-v2/connector-cdc/connector-cdc-mongodb/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/mongodb/config/MongodbIncrementalSourceOptions.java
index 2602449a7b..bdd1f00d73 100644
--- a/seatunnel-connectors-v2/connector-cdc/connector-cdc-mongodb/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/mongodb/config/MongodbIncrementalSourceOptions.java
+++ b/seatunnel-connectors-v2/connector-cdc/connector-cdc-mongodb/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/mongodb/config/MongodbIncrementalSourceOptions.java
@@ -26,7 +26,6 @@ import org.apache.seatunnel.connectors.cdc.base.option.StartupMode;
 import org.apache.seatunnel.connectors.cdc.base.option.StopMode;
 
 import java.util.Arrays;
-import java.util.Collections;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
@@ -150,9 +149,11 @@ public class MongodbIncrementalSourceOptions extends SourceOptions implements Ta
 
     public static final SingleChoiceOption<StopMode> STOP_MODE =
             Options.key(SourceOptions.STOP_MODE_KEY)
-                    .singleChoice(StopMode.class, Collections.singletonList(StopMode.NEVER))
+                    .singleChoice(StopMode.class, Arrays.asList(StopMode.NEVER, StopMode.TIMESTAMP))
                     .defaultValue(StopMode.NEVER)
                     .withDescription(
-                            "Optional stop mode for CDC source, valid enumerations are "
-                                    + "\"never\", \"latest\", \"timestamp\"\n or \"specific\"");
+                            "Optional stop mode for MongoDB CDC source, valid enumerations are "
+                                    + "\"never\" or \"timestamp\". "
+                                    + "\"never\": keeps reading the change stream. "
+                                    + "\"timestamp\": stops after reaching the change-stream position given by \"stop.timestamp\".");
 }
diff --git a/seatunnel-connectors-v2/connector-cdc/connector-cdc-mongodb/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/mongodb/config/MongodbSourceConfigProvider.java b/seatunnel-connectors-v2/connector-cdc/connector-cdc-mongodb/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/mongodb/config/MongodbSourceConfigProvider.java
index 7226bd2f26..f0cb055b3a 100644
--- a/seatunnel-connectors-v2/connector-cdc/connector-cdc-mongodb/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/mongodb/config/MongodbSourceConfigProvider.java
+++ b/seatunnel-connectors-v2/connector-cdc/connector-cdc-mongodb/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/mongodb/config/MongodbSourceConfigProvider.java
@@ -22,7 +22,9 @@ import org.apache.seatunnel.connectors.cdc.base.config.StartupConfig;
 import org.apache.seatunnel.connectors.cdc.base.config.StopConfig;
 import org.apache.seatunnel.connectors.cdc.base.option.StartupMode;
 import org.apache.seatunnel.connectors.cdc.base.option.StopMode;
+import org.apache.seatunnel.connectors.cdc.base.source.offset.Offset;
 import org.apache.seatunnel.connectors.seatunnel.cdc.mongodb.exception.MongodbConnectorException;
+import org.apache.seatunnel.connectors.seatunnel.cdc.mongodb.source.offset.ChangeStreamOffsetFactory;
 
 import java.util.List;
 import java.util.Objects;
@@ -124,7 +126,8 @@ public class MongodbSourceConfigProvider {
 
         public Builder stopOptions(StopConfig stopOptions) {
             this.stopOptions = Objects.requireNonNull(stopOptions);
-            if (stopOptions.getStopMode() != StopMode.NEVER) {
+            if (stopOptions.getStopMode() != StopMode.NEVER
+                    && stopOptions.getStopMode() != StopMode.TIMESTAMP) {
                 throw new MongodbConnectorException(
                         ILLEGAL_ARGUMENT,
                         String.format("The %s mode is not supported.", stopOptions.getStopMode()));
@@ -146,6 +149,29 @@ public class MongodbSourceConfigProvider {
 
         public Builder validate() {
             checkNotNull(hosts, "hosts must be provided");
+            if (startupOptions != null
+                    && stopOptions != null
+                    && startupOptions.getStartupMode() == StartupMode.TIMESTAMP
+                    && stopOptions.getStopMode() == StopMode.TIMESTAMP) {
+                // Compare the derived offsets because MongoDB change-stream timestamps have second
+                // precision and two different millisecond values can resolve to the same position.
+                ChangeStreamOffsetFactory offsetFactory = new ChangeStreamOffsetFactory();
+                Offset startupOffset = startupOptions.getStartupOffset(offsetFactory);
+                Offset stopOffset = stopOptions.getStopOffset(offsetFactory);
+                if (stopOffset.compareTo(startupOffset) <= 0) {
+                    throw new MongodbConnectorException(
+                            ILLEGAL_ARGUMENT,
+                            String.format(
+                                    "Invalid timestamp range: stop.timestamp (%d) resolves to "
+                                            + "MongoDB position %s, which must be after "
+                                            + "startup.timestamp (%d) at position %s. MongoDB "
+                                            + "change-stream timestamps have second precision.",
+                                    stopOptions.getTimestamp(),
+                                    stopOffset,
+                                    startupOptions.getTimestamp(),
+                                    startupOffset));
+                }
+            }
             return this;
         }
 
diff --git a/seatunnel-connectors-v2/connector-cdc/connector-cdc-mongodb/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/mongodb/source/fetch/MongodbStreamFetchTask.java b/seatunnel-connectors-v2/connector-cdc/connector-cdc-mongodb/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/mongodb/source/fetch/MongodbStreamFetchTask.java
index 2d90c0eeea..4abb738569 100644
--- a/seatunnel-connectors-v2/connector-cdc/connector-cdc-mongodb/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/mongodb/source/fetch/MongodbStreamFetchTask.java
+++ b/seatunnel-connectors-v2/connector-cdc/connector-cdc-mongodb/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/mongodb/source/fetch/MongodbStreamFetchTask.java
@@ -17,6 +17,7 @@
 
 package org.apache.seatunnel.connectors.seatunnel.cdc.mongodb.source.fetch;
 
+import org.apache.seatunnel.connectors.cdc.base.source.offset.Offset;
 import org.apache.seatunnel.connectors.cdc.base.source.reader.external.FetchTask;
 import org.apache.seatunnel.connectors.cdc.base.source.split.IncrementalSplit;
 import org.apache.seatunnel.connectors.cdc.base.source.split.SourceSplitBase;
@@ -202,7 +203,7 @@ public class MongodbStreamFetchTask implements FetchTask<SourceSplitBase> {
                     if (changeRecord != null) {
                         currentOffset = new ChangeStreamOffset(getResumeToken(changeRecord));
                         // The log after the high watermark won't emit.
-                        if (currentOffset.isAtOrBefore(streamSplit.getStopOffset())) {
+                        if (shouldEmit(currentOffset, streamSplit.getStopOffset())) {
                             queue.enqueue(new DataChangeEvent(changeRecord));
                         }
                     } else {
@@ -211,7 +212,7 @@ public class MongodbStreamFetchTask implements FetchTask<SourceSplitBase> {
                     }
 
                     // Reach the high watermark, the binlog fetcher should be finished
-                    if (currentOffset.isAtOrAfter(streamSplit.getStopOffset())) {
+                    if (hasReachedStop(currentOffset, streamSplit.getStopOffset())) {
                         // send watermark end event
                         SourceRecord watermark =
                                 WatermarkEvent.create(
@@ -237,6 +238,14 @@ public class MongodbStreamFetchTask implements FetchTask<SourceSplitBase> {
         }
     }
 
+    static boolean shouldEmit(ChangeStreamOffset currentOffset, Offset stopOffset) {
+        return currentOffset.isAtOrBefore(stopOffset);
+    }
+
+    static boolean hasReachedStop(ChangeStreamOffset currentOffset, Offset stopOffset) {
+        return currentOffset.isAtOrAfter(stopOffset);
+    }
+
     @Override
     public boolean isRunning() {
         return taskRunning;
diff --git a/seatunnel-connectors-v2/connector-cdc/connector-cdc-mongodb/src/test/java/mongodb/source/MongodbIncrementalSourceFactoryTest.java b/seatunnel-connectors-v2/connector-cdc/connector-cdc-mongodb/src/test/java/mongodb/source/MongodbIncrementalSourceFactoryTest.java
index 7fe549f80a..f40f4194f3 100644
--- a/seatunnel-connectors-v2/connector-cdc/connector-cdc-mongodb/src/test/java/mongodb/source/MongodbIncrementalSourceFactoryTest.java
+++ b/seatunnel-connectors-v2/connector-cdc/connector-cdc-mongodb/src/test/java/mongodb/source/MongodbIncrementalSourceFactoryTest.java
@@ -19,8 +19,10 @@ package mongodb.source;
 
 import org.apache.seatunnel.api.configuration.SingleChoiceOption;
 import org.apache.seatunnel.connectors.cdc.base.config.StartupConfig;
+import org.apache.seatunnel.connectors.cdc.base.config.StopConfig;
 import org.apache.seatunnel.connectors.cdc.base.option.SourceOptions;
 import org.apache.seatunnel.connectors.cdc.base.option.StartupMode;
+import org.apache.seatunnel.connectors.cdc.base.option.StopMode;
 import org.apache.seatunnel.connectors.cdc.base.source.offset.Offset;
 import org.apache.seatunnel.connectors.seatunnel.cdc.mongodb.MongodbIncrementalSourceFactory;
 import org.apache.seatunnel.connectors.seatunnel.cdc.mongodb.config.MongodbSourceConfig;
@@ -57,6 +59,19 @@ public class MongodbIncrementalSourceFactoryTest {
                         });
     }
 
+    @Test
+    public void testSupportedStopModes() {
+        MongodbIncrementalSourceFactory mongodbIncrementalSourceFactory =
+                new MongodbIncrementalSourceFactory();
+        mongodbIncrementalSourceFactory.optionRule().getOptionalOptions().stream()
+                .filter((option) -> option.key().equals(SourceOptions.STOP_MODE_KEY))
+                .forEach(
+                        (option) ->
+                                Assertions.assertIterableEquals(
+                                        Arrays.asList(StopMode.NEVER, StopMode.TIMESTAMP),
+                                        ((SingleChoiceOption<StopMode>) option).getOptionValues()));
+    }
+
     @Test
     public void testSourceConfigBuilderAcceptsLatestStartupMode() {
         // Regression for the real source-assembly path: the builder used to reject
@@ -93,4 +108,114 @@ public class MongodbIncrementalSourceFactoryTest {
         Assertions.assertNotNull(((ChangeStreamOffset) startupOffset).getTimestamp());
         Assertions.assertNull(((ChangeStreamOffset) startupOffset).getResumeToken());
     }
+
+    @Test
+    public void testSourceConfigBuilderAcceptsTimestampStopMode() {
+        long stopTimestamp = 1_700_000_000_000L;
+        StopConfig stopConfig = new StopConfig(StopMode.TIMESTAMP, null, null, stopTimestamp);
+
+        MongodbSourceConfig config =
+                MongodbSourceConfigProvider.newBuilder()
+                        .hosts("localhost:27017")
+                        .stopOptions(stopConfig)
+                        .validate()
+                        .create(0);
+
+        Assertions.assertEquals(StopMode.TIMESTAMP, config.getStopConfig().getStopMode());
+        ChangeStreamOffset stopOffset =
+                (ChangeStreamOffset)
+                        config.getStopConfig().getStopOffset(new ChangeStreamOffsetFactory());
+        Assertions.assertEquals(
+                stopTimestamp / 1000, Integer.toUnsignedLong(stopOffset.getTimestamp().getTime()));
+    }
+
+    @Test
+    public void testSourceConfigBuilderAcceptsTimestampRange() {
+        MongodbSourceConfig config =
+                MongodbSourceConfigProvider.newBuilder()
+                        .hosts("localhost:27017")
+                        .startupOptions(
+                                new StartupConfig(
+                                        StartupMode.TIMESTAMP, null, null, 1_700_000_000_000L))
+                        .stopOptions(
+                                new StopConfig(StopMode.TIMESTAMP, null, null, 1_700_000_001_000L))
+                        .validate()
+                        .create(0);
+
+        Assertions.assertEquals(StartupMode.TIMESTAMP, config.getStartupConfig().getStartupMode());
+        Assertions.assertEquals(StopMode.TIMESTAMP, config.getStopConfig().getStopMode());
+    }
+
+    @Test
+    public void testSourceConfigBuilderRejectsInvalidTimestampRange() {
+        long startupTimestamp = 1_700_000_000_000L;
+
+        Assertions.assertThrows(
+                MongodbConnectorException.class,
+                () ->
+                        MongodbSourceConfigProvider.newBuilder()
+                                .hosts("localhost:27017")
+                                .startupOptions(
+                                        new StartupConfig(
+                                                StartupMode.TIMESTAMP,
+                                                null,
+                                                null,
+                                                startupTimestamp))
+                                .stopOptions(
+                                        new StopConfig(
+                                                StopMode.TIMESTAMP, null, null, startupTimestamp))
+                                .validate());
+        Assertions.assertThrows(
+                MongodbConnectorException.class,
+                () ->
+                        MongodbSourceConfigProvider.newBuilder()
+                                .hosts("localhost:27017")
+                                .startupOptions(
+                                        new StartupConfig(
+                                                StartupMode.TIMESTAMP,
+                                                null,
+                                                null,
+                                                startupTimestamp))
+                                .stopOptions(
+                                        new StopConfig(
+                                                StopMode.TIMESTAMP,
+                                                null,
+                                                null,
+                                                startupTimestamp - 1000L))
+                                .validate());
+        MongodbConnectorException sameSecondException =
+                Assertions.assertThrows(
+                        MongodbConnectorException.class,
+                        () ->
+                                MongodbSourceConfigProvider.newBuilder()
+                                        .hosts("localhost:27017")
+                                        .startupOptions(
+                                                new StartupConfig(
+                                                        StartupMode.TIMESTAMP,
+                                                        null,
+                                                        null,
+                                                        startupTimestamp))
+                                        .stopOptions(
+                                                new StopConfig(
+                                                        StopMode.TIMESTAMP,
+                                                        null,
+                                                        null,
+                                                        startupTimestamp + 500L))
+                                        .validate());
+        Assertions.assertTrue(sameSecondException.getMessage().contains("second precision"));
+    }
+
+    @Test
+    public void testSourceConfigBuilderRejectsUnsupportedStopMode() {
+        Assertions.assertThrows(
+                MongodbConnectorException.class,
+                () ->
+                        MongodbSourceConfigProvider.newBuilder()
+                                .stopOptions(new StopConfig(StopMode.SPECIFIC, null, null, null)));
+        Assertions.assertThrows(
+                MongodbConnectorException.class,
+                () ->
+                        MongodbSourceConfigProvider.newBuilder()
+                                .stopOptions(new StopConfig(StopMode.LATEST, null, null, null)));
+    }
 }
diff --git a/seatunnel-connectors-v2/connector-cdc/connector-cdc-mongodb/src/test/java/org/apache/seatunnel/connectors/seatunnel/cdc/mongodb/source/fetch/MongodbStreamFetchTaskTest.java b/seatunnel-connectors-v2/connector-cdc/connector-cdc-mongodb/src/test/java/org/apache/seatunnel/connectors/seatunnel/cdc/mongodb/source/fetch/MongodbStreamFetchTaskTest.java
new file mode 100644
index 0000000000..f71bcb6d8e
--- /dev/null
+++ b/seatunnel-connectors-v2/connector-cdc/connector-cdc-mongodb/src/test/java/org/apache/seatunnel/connectors/seatunnel/cdc/mongodb/source/fetch/MongodbStreamFetchTaskTest.java
@@ -0,0 +1,37 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.seatunnel.connectors.seatunnel.cdc.mongodb.source.fetch;
+
+import org.apache.seatunnel.connectors.seatunnel.cdc.mongodb.source.offset.ChangeStreamOffset;
+
+import org.bson.BsonTimestamp;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+/** Verifies bounded change-stream stop semantics. */
+class MongodbStreamFetchTaskTest {
+
+    @Test
+    void testRecordAtStopOffsetIsEmittedBeforeStopping() {
+        ChangeStreamOffset stopOffset = new ChangeStreamOffset(new BsonTimestamp(100, 1));
+        ChangeStreamOffset currentOffset = new ChangeStreamOffset(new BsonTimestamp(100, 1));
+
+        Assertions.assertTrue(MongodbStreamFetchTask.shouldEmit(currentOffset, stopOffset));
+        Assertions.assertTrue(MongodbStreamFetchTask.hasReachedStop(currentOffset, stopOffset));
+    }
+}
diff --git a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-cdc-mongodb-e2e/src/test/java/mongodb/MongodbCDCIT.java b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-cdc-mongodb-e2e/src/test/java/mongodb/MongodbCDCIT.java
index b04a6d37c6..d55819da3b 100644
--- a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-cdc-mongodb-e2e/src/test/java/mongodb/MongodbCDCIT.java
+++ b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-cdc-mongodb-e2e/src/test/java/mongodb/MongodbCDCIT.java
@@ -72,6 +72,8 @@ import java.sql.ResultSet;
 import java.sql.SQLException;
 import java.sql.Statement;
 import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
@@ -83,6 +85,7 @@ import java.util.concurrent.TimeUnit;
 import java.util.stream.Collectors;
 import java.util.stream.Stream;
 
+import static org.apache.seatunnel.connectors.seatunnel.cdc.mongodb.utils.MongodbUtils.getCurrentClusterTime;
 import static org.testcontainers.shaded.org.awaitility.Awaitility.await;
 import static org.testcontainers.shaded.org.awaitility.Awaitility.with;
 import static org.testcontainers.shaded.org.awaitility.Durations.TWO_SECONDS;
@@ -190,6 +193,123 @@ public class MongodbCDCIT extends TestSuiteBase implements TestResource {
         assertionsSourceAndSink(MONGODB_COLLECTION_1, SINK_SQL_PRODUCTS);
     }
 
+    @TestTemplate
+    @DisabledOnContainer(
+            value = {},
+            type = {EngineType.FLINK, EngineType.SPARK},
+            disabledReason =
+                    "Currently FLINK and SPARK do not support restore and bounded incremental split termination")
+    public void testMongodbCdcTimestampStopMode(TestContainer container) throws Exception {
+        cleanSourceTable();
+
+        long startupTimestamp = currentClusterTimeMillis();
+
+        MongoCollection<Document> products =
+                client.getDatabase(MONGODB_DATABASE).getCollection(MONGODB_COLLECTION_1);
+        products.insertMany(
+                Arrays.asList(
+                        new Document("_id", new ObjectId("100000000000000000000130"))
+                                .append("name", "bounded-before-1")
+                                .append("description", "before stop timestamp")
+                                .append("weight", "10"),
+                        new Document("_id", new ObjectId("100000000000000000000131"))
+                                .append("name", "bounded-before-2")
+                                .append("description", "before stop timestamp")
+                                .append("weight", "20")));
+
+        long stopTimestamp = currentClusterTimeMillis() + TimeUnit.SECONDS.toMillis(240);
+        String jobId = String.valueOf(JobIdGenerator.newJobId());
+        String[] variables = {
+            "startup_timestamp=" + startupTimestamp, "stop_timestamp=" + stopTimestamp
+        };
+
+        CompletableFuture<Container.ExecResult> jobFuture =
+                CompletableFuture.supplyAsync(
+                        () -> {
+                            try {
+                                return container.executeJob(
+                                        "/mongodbcdc_stop_mode_timestamp.conf", jobId, variables);
+                            } catch (Exception e) {
+                                throw new CompletionException(e);
+                            }
+                        });
+
+        await().atMost(30, TimeUnit.SECONDS)
+                .untilAsserted(
+                        () -> {
+                            if (jobFuture.isDone()) {
+                                Container.ExecResult jobResult = jobFuture.get();
+                                Assertions.fail(
+                                        "The bounded MongoDB CDC job terminated before reaching RUNNING: "
+                                                + jobResult.getStderr());
+                            }
+                            Assertions.assertEquals("RUNNING", container.getJobStatus(jobId));
+                        });
+
+        await().atMost(60, TimeUnit.SECONDS)
+                .untilAsserted(
+                        () ->
+                                Assertions.assertIterableEquals(
+                                        Arrays.asList(
+                                                Collections.singletonList("bounded-before-1"),
+                                                Collections.singletonList("bounded-before-2")),
+                                        querySql(
+                                                "select name from products where name like 'bounded-before-%' order by name")));
+
+        Assertions.assertEquals(0, container.savepointJob(jobId).getExitCode());
+        products.insertOne(
+                new Document("_id", new ObjectId("100000000000000000000133"))
+                        .append("name", "bounded-after-restore")
+                        .append("description", "after savepoint restore")
+                        .append("weight", "25"));
+
+        CompletableFuture<Container.ExecResult> restoredJobFuture =
+                CompletableFuture.supplyAsync(
+                        () -> {
+                            try {
+                                return container.restoreJob(
+                                        "/mongodbcdc_stop_mode_timestamp.conf", jobId, variables);
+                            } catch (Exception e) {
+                                throw new CompletionException(e);
+                            }
+                        });
+
+        await().atMost(60, TimeUnit.SECONDS)
+                .untilAsserted(
+                        () ->
+                                Assertions.assertIterableEquals(
+                                        Collections.singletonList(
+                                                Collections.singletonList("bounded-after-restore")),
+                                        querySql(
+                                                "select name from products where name = 'bounded-after-restore'")));
+
+        await().atMost(240, TimeUnit.SECONDS)
+                .until(() -> currentClusterTimeMillis() > stopTimestamp);
+        products.insertOne(
+                new Document("_id", new ObjectId("100000000000000000000132"))
+                        .append("name", "bounded-after")
+                        .append("description", "after stop timestamp")
+                        .append("weight", "30"));
+
+        Container.ExecResult result = restoredJobFuture.get(120, TimeUnit.SECONDS);
+        Assertions.assertEquals(0, result.getExitCode(), result.getStderr());
+        await().atMost(30, TimeUnit.SECONDS)
+                .untilAsserted(
+                        () -> Assertions.assertEquals("FINISHED", container.getJobStatus(jobId)));
+        Assertions.assertIterableEquals(
+                Arrays.asList(
+                        Collections.singletonList("bounded-after-restore"),
+                        Collections.singletonList("bounded-before-1"),
+                        Collections.singletonList("bounded-before-2")),
+                querySql("select name from products where name like 'bounded-%' order by name"),
+                "the bounded result must contain only events before the stop timestamp");
+    }
+
+    private long currentClusterTimeMillis() {
+        // Use the MongoDB server clock and retain its second precision to match the stop offset.
+        return Integer.toUnsignedLong(getCurrentClusterTime(client).getTime()) * 1000L;
+    }
+
     @TestTemplate
     public void testMongodbCdcMultiTableToMysqlE2e(TestContainer container)
             throws InterruptedException {
diff --git a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-cdc-mongodb-e2e/src/test/resources/mongodbcdc_stop_mode_timestamp.conf b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-cdc-mongodb-e2e/src/test/resources/mongodbcdc_stop_mode_timestamp.conf
new file mode 100644
index 0000000000..d2ea39e0c4
--- /dev/null
+++ b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-cdc-mongodb-e2e/src/test/resources/mongodbcdc_stop_mode_timestamp.conf
@@ -0,0 +1,61 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+env {
+  parallelism = 1
+  job.mode = "STREAMING"
+  checkpoint.interval = 5000
+}
+
+source {
+  MongoDB-CDC {
+    hosts = "mongo0:27017"
+    database = ["inventory"]
+    collection = ["inventory.products"]
+    username = superuser
+    password = superpw
+    startup.mode = "timestamp"
+    startup.timestamp = ${startup_timestamp}
+    stop.mode = "timestamp"
+    stop.timestamp = ${stop_timestamp}
+    schema = {
+      primaryKey {
+        name = "id"
+        columnNames = ["_id"]
+      }
+      fields {
+        "_id": string,
+        "name": string,
+        "description": string,
+        "weight": string
+      }
+    }
+  }
+}
+
+sink {
+  jdbc {
+    url = "jdbc:mysql://mysql_e2e:3306/mongodb_cdc"
+    driver = "com.mysql.cj.jdbc.Driver"
+    username = "st_user"
+    password = "seatunnel"
+    generate_sink_sql = true
+    database = mongodb_cdc
+    table = products
+    primary_keys = ["_id"]
+  }
+}