Data Transmission Service (DTS) lets you synchronize data from a MongoDB sharded cluster to a replica set or sharded cluster. This topic shows you how to synchronize data between ApsaraDB for MongoDB instances.
Prerequisites
-
Create a target ApsaraDB for MongoDB instance (replica set or sharded cluster). For more information, see Create a replica set instance or Create a sharded cluster instance.
Important-
The storage space of the target ApsaraDB for MongoDB instance should be at least 10% larger than that of the source ApsaraDB for MongoDB instance.
-
For supported versions, see Data synchronization scenarios.
-
-
For a source ApsaraDB for MongoDB sharded cluster instance, apply for an endpoint for each shard node and ensure that all shard nodes use the same account and password. For more information, see Apply for a shard endpoint.
-
If the target is a sharded cluster instance, you must create the databases and collections to be sharded in the target ApsaraDB for MongoDB (sharded cluster) instance, configure data sharding, enable the balancer, and perform pre-sharding based on your business requirements. For more information, see Configure sharding to maximize shard performance and How do I handle uneven data distribution in a sharded MongoDB cluster?.
Note-
Configuring data sharding prevents all data from synchronizing to a single shard, which avoids performance bottlenecks. Enabling the balancer and performing pre-sharding helps prevent data skew.
-
This topic provides an example of configuring a DTS task before purchase. In this scenario, you do not need to specify the number of shards in the source ApsaraDB for MongoDB (sharded cluster) instance.
If you purchase a DTS task before you configure it, you must specify the correct number of shards at the time of purchase.
-
Precautions
Type | Description |
Source and destination database limits |
|
Other limits |
|
Billing
|
Synchronization type |
Pricing |
|
Schema synchronization and full data synchronization |
Free of charge. |
|
Incremental data synchronization |
Charged. For more information, see Billing overview. |
One-way synchronization topologies
DTS only supports one-way data synchronization between two ApsaraDB for MongoDB sharded cluster instances. Synchronization among multiple ApsaraDB for MongoDB instances is not supported.
Synchronization types
|
Type |
Description |
|
Schema synchronization |
Synchronize the schema of the synchronization objects in the source ApsaraDB for MongoDB to the target ApsaraDB for MongoDB. |
|
Full data synchronization |
Synchronizes all existing data of the synchronization objects from the source ApsaraDB for MongoDB to the destination ApsaraDB for MongoDB. Note
Full data synchronization is supported for databases and collections. |
|
Incremental data synchronization |
Based on the full data synchronization, incremental updates from the source ApsaraDB for MongoDB are synchronized to the target ApsaraDB for MongoDB. OplogIncremental data synchronization does not replicate databases created after the task starts. The following changes are replicated:
Change streamThe following changes are replicated:
|
Clean up orphaned documents
Clean up orphaned documents from the source MongoDB database before you migrate data.
Failure to clean up orphaned documents affects migration performance and can cause data migration errors due to _id conflicts.
ApsaraDB for MongoDB
Running the cleanup script on an instance with a major version earlier than MongoDB 4.2 or a minor version earlier than 4.0.6 causes an error. To view the current version of your instance, see MongoDB minor versions. To upgrade the major or minor version, see Upgrade the major version of a database and Upgrade the minor version of a database.
Use the cleanupOrphaned command to clean up orphaned documents. The procedure differs slightly for MongoDB 4.4 and later and for MongoDB 4.2 and earlier.
MongoDB 4.4 and later
-
On a server that can connect to your sharded cluster instance, create a JavaScript (JS) script named
cleanupOrphaned.js.NoteThis script cleans up orphaned documents from all collections in multiple databases across multiple shards. If you need to clean up orphaned documents from a specific collection, you can modify the JS script.
// List of shard names var shardNames = ["shardName1", "shardName2"]; // List of databases var databasesToProcess = ["database1", "database2", "database3"]; shardNames.forEach(function(shardName) { // Iterate over the specified list of databases databasesToProcess.forEach(function(dbName) { var dbInstance = db.getSiblingDB(dbName); // Get the names of all collections in the database instance var collectionNames = dbInstance.getCollectionNames(); // Iterate over each collection collectionNames.forEach(function(collectionName) { // The full collection name var fullCollectionName = dbName + "." + collectionName; // Build the cleanupOrphaned command var command = { runCommandOnShard: shardName, command: { cleanupOrphaned: fullCollectionName } }; // Execute the command var result = db.adminCommand(command); if (result.ok) { print("Cleaned up orphaned documents for collection " + fullCollectionName + " on shard " + shardName); printjson(result); } else { print("Failed to clean up orphaned documents for collection " + fullCollectionName + " on shard " + shardName); } }); }); });In the script, modify the values of the
shardNamesanddatabasesToProcessparameters:-
shardNames: An array of IDs for the shards from which to clean up orphaned documents. You can obtain the shard IDs from the Shard List on the Basic Information page of the instance. For example,d-bp15a3796d3a****. -
databasesToProcess: An array of database names from which to clean up orphaned documents.
-
-
In the directory where the
cleanupOrphaned.jsscript is located, run the following command to clean up orphaned documents.mongo --host <Mongoshost> --port <Primaryport> --authenticationDatabase <database> -u <username> -p <password> cleanupOrphaned.js > output.txtParameter
Description
<Mongoshost>The connection address of the mongos node of the sharded cluster instance. Example:
s-bp14423a2a51****.mongodb.rds.aliyuncs.com.<Primaryport>The port number of the mongos node of the sharded cluster instance. The default value is 3717.
<database>The name of the authentication database. This is the database to which the database account belongs.
<username>The database account.
<password>The password for the database account.
output.txtThe output file for the execution results.
MongoDB 4.2 and earlier
-
On a server that can connect to your sharded cluster instance, create a JS script named
cleanupOrphaned.js.NoteThis script cleans up orphaned documents from a specified collection in a specified database across multiple shards. To clean up orphaned documents from multiple collections, you can modify the
fullCollectionNameparameter and run the script multiple times, or modify the script to iterate through the collections.function cleanupOrphanedOnShard(shardName, fullCollectionName) { var nextKey = { }; var result; while ( nextKey != null ) { var command = { runCommandOnShard: shardName, command: { cleanupOrphaned: fullCollectionName, startingFromKey: nextKey } }; result = db.adminCommand(command); printjson(result); if (result.ok != 1 || !(result.results.hasOwnProperty(shardName)) || result.results[shardName].ok != 1 ) { print("Unable to complete at this time: failure or timeout.") break } nextKey = result.results[shardName].stoppedAtKey; } print("cleanupOrphaned done for coll: " + fullCollectionName + " on shard: " + shardName) } var shardNames = ["shardName1", "shardName2", "shardName3"] var fullCollectionName = "database.collection" shardNames.forEach(function(shardName) { cleanupOrphanedOnShard(shardName, fullCollectionName); });In the script, modify the values of the
shardNamesandfullCollectionNameparameters:-
shardNames: An array of IDs for the shards from which to clean up orphaned documents. You can obtain the shard IDs from the Shard List on the Basic Information page of the instance. For example,d-bp15a3796d3a****. -
fullCollectionName: The name of the collection from which to clean up orphaned documents, in the formatdatabase.collection.
-
-
In the directory where the
cleanupOrphaned.jsscript is located, run the following command to clean up orphaned documents.mongo --host <Mongoshost> --port <Primaryport> --authenticationDatabase <database> -u <username> -p <password> cleanupOrphaned.js > output.txtParameter
Description
<Mongoshost>The connection address of the mongos node of the sharded cluster instance. Example:
s-bp14423a2a51****.mongodb.rds.aliyuncs.com.<Primaryport>The port number of the mongos node of the sharded cluster instance. The default value is 3717.
<database>The name of the authentication database. This is the database to which the database account belongs.
<username>The database account.
<password>The password for the database account.
output.txtThe output file for the execution results.
Self-managed MongoDB
-
On a server that can connect to your self-managed MongoDB database, download the cleanupOrphaned.js script file.
wget "https://docs-aliyun.cn-hangzhou.oss.aliyun-inc.com/assets/attach/120562/cn_zh/1564451237979/cleanupOrphaned.js" -
Modify the cleanupOrphaned.js script file. Replace
testwith the name of the database from which you want to clean up orphaned documents.ImportantIf you have multiple databases, you must repeat Step 2 and Step 3 for each database.
function cleanupOrphaned(coll) { var nextKey = { }; var result; while ( nextKey != null ) { result = db.adminCommand( { cleanupOrphaned: coll, startingFromKey: nextKey } ); if (result.ok != 1) print("Unable to complete at this time: failure or timeout.") printjson(result); nextKey = result.stoppedAtKey; } } var dbName = "test" db = db.getSiblingDB(dbName) db.getCollectionNames().forEach(function(collName) { cleanupOrphaned(dbName + "." + collName); }); -
Run the following command to clean up orphaned documents from all collections in the specified database on a shard.
NoteYou must repeat this step for each shard.
mongo --host <Shardhost> --port <Primaryport> --authenticationDatabase <database> -u <username> -p <password> cleanupOrphaned.jsNote-
<Shardhost>: The IP address of the shard.
-
<Primaryport>: The service port of the primary node in the shard.
-
<database>: The name of the authentication database. This is the database to which the database account belongs.
-
<username>: The database account.
-
<password>: The password for the account.
Example:
In this example, the self-managed MongoDB database has three shards. You must run the command for each shard to clean up the orphaned documents.
mongo --host 172.16.1.10 --port 27018 --authenticationDatabase admin -u dtstest -p 'Test123456' cleanupOrphaned.jsmongo --host 172.16.1.11 --port 27021 --authenticationDatabase admin -u dtstest -p 'Test123456' cleanupOrphaned.jsmongo --host 172.16.1.12 --port 27024 --authenticationDatabase admin -u dtstest -p 'Test123456' cleanupOrphaned.js -
Procedure
This topic uses an example of configuring a DTS task before purchasing it, where you do not need to specify the number of shards for the source ApsaraDB for MongoDB sharded cluster.
If you purchase a DTS task before you configure it, you must specify the correct number of shards at the time of purchase.
-
Navigate to the migration task list page for the destination region using one of the following methods.
From the DTS console
-
Log on to the Data Transmission Service (DTS) console.
-
In the navigation pane on the left, click Data Migration.
-
In the upper-left corner of the page, select the region where the migration instance is located.
From the DMS console
NoteThe actual operations may vary based on the mode and layout of the DMS console. For more information, see Simple mode console and Customize the layout and style of the DMS console.
-
Log on to the Data Management (DMS) console.
-
In the top menu bar, choose .
-
To the right of Data Migration Tasks, select the region where the migration instance is located.
-
-
Click Create Task and configure the source and destination databases.
Section
Parameter
Description
N/A
Task Name
DTS automatically generates a task name. We recommend that you specify a descriptive name for easy identification. The name does not need to be unique.
Source Database
Select an existing DMS database instance. (Optional. If you have not registered a DMS database instance, ignore this option and configure database settings in the section below.) (Optional. If you have not created a connection, you can skip this and directly configure the database information below.)
Choose whether to use an existing instance as needed.
If you use an existing instance, the database information is automatically filled in. You do not need to enter it again.
If you do not use an existing instance, enter the database information below.
Database Type
Select MongoDB.
Access Method
Select Alibaba Cloud Instance.
Instance Region
Select the region where the source ApsaraDB for MongoDB instance is located.
Replicate Data Across Alibaba Cloud Accounts
This example shows how to synchronize data within the same Alibaba Cloud account. Select No.
Architecture
Select Sharded Cluster.
Migration Method
Select a method for incremental data synchronization based on your requirements.
-
Oplog (Recommended):
This option is available if Oplog is enabled for the source database.
NoteOplog is enabled by default for self-managed MongoDB databases and ApsaraDB for MongoDB instances. This method offers lower latency for incremental synchronization tasks because logs are retrieved faster. We recommend selecting Oplog.
-
ChangeStream:
This option is available if Change Streams are enabled for the source database.
Note-
If the source database is an Amazon DocumentDB (non-elastic cluster) instance, you can select only ChangeStream.
-
If you set Architecture of the source database to Sharded Cluster, you do not need to specify Shard account and Shard password.
-
Instance ID
Select the instance ID of the source ApsaraDB for MongoDB instance.
Database Name
Enter the name of the database to which the database account of the source ApsaraDB for MongoDB instance belongs. The default value is admin.
Database Account
Enter the database account of the source ApsaraDB for MongoDB instance. This account must have read permissions on the database to be synchronized, as well as on the config, admin, and local databases.
NoteIf you use ChangeStream as the incremental synchronization method, the source database account requires instance-wide Change Streams read permissions (such as
readAnyDatabase). If the source is an ApsaraDB for MongoDB instance with a custom account, you must also grant the account read permission on theadmindatabase. For details, see Permissions of the root account specified during instance creation.Database Password
Enter the password for the specified database account.
Shard account
Enter the shard account of the source ApsaraDB for MongoDB instance.
NoteIf your source is a self-managed MongoDB database, you must also enter the shard connection information for the shard nodes.
Shard password
Enter the shard password for the source ApsaraDB for MongoDB instance.
Destination Database
Select an existing DMS database instance. (Optional. If you have not registered a DMS database instance, ignore this option and configure database settings in the section below.) (Optional. If you have not created a connection, you can skip this and directly configure the database information below.)
Choose whether to use an existing instance as needed.
If you use an existing instance, the database information is automatically filled in. You do not need to enter it again.
If you do not use an existing instance, enter the database information below.
Database Type
Select MongoDB.
Access Method
Select Alibaba Cloud Instance.
Instance Region
Select the region where the destination ApsaraDB for MongoDB instance is located.
Architecture
Select the architecture type of the destination ApsaraDB for MongoDB instance.
Instance ID
Select the instance ID of the destination ApsaraDB for MongoDB instance.
Database Name
Enter the name of the database to which the database account of the destination ApsaraDB for MongoDB instance belongs. The default value is admin.
Database Account
Enter the database account of the destination ApsaraDB for MongoDB instance. This account requires the dbAdminAnyDatabase permission, read-write permissions on the destination database, and read permissions on the local database.
Database Password
Enter the password for the specified database account.
Encryption
DTS supports three connection methods: Non-encrypted, SSL-encrypted, and Mongo Atlas SSL. The options for Encryption vary based on the selected Access Method and Architecture. The options displayed in the console prevail.
Note-
MongoDB databases with an Architecture of Sharded Cluster do not support SSL-encrypted.
-
If the destination is a self-managed MongoDB database (Access Method is not Alibaba Cloud Instance) with a Replica Set, and you select SSL-encrypted, DTS also allows you to upload a CA certificate to verify the connection.
-
In the lower part of the page, click Test Connectivity and Proceed.
If the source or destination database is an Alibaba Cloud database instance, such as an ApsaraDB RDS for MySQL or ApsaraDB for MongoDB instance, DTS automatically adds the CIDR blocks of DTS servers to the whitelist of the instance. If the source or destination database is a self-managed database hosted on an Elastic Compute Service (ECS) instance, DTS automatically adds the CIDR blocks of DTS servers to the security group rules of the ECS instance, and you must ensure that the ECS instance can access the database. If the source or destination database is a self-managed database that is deployed in a data center or provided by a third-party cloud service provider, you must manually add the CIDR blocks of DTS servers to the whitelist of the database to allow DTS to access the database. For more information, see Whitelist DTS server IP addresses.
WarningIf the CIDR blocks of DTS servers are automatically or manually added to the whitelist of the database or instance, or to the ECS security group rules, security risks may arise. Therefore, before you use DTS to synchronize data, you must understand and acknowledge the potential risks and take preventive measures, including but not limited to the following measures: enhancing the security of your username and password, limiting the ports that are exposed, authenticating API calls, regularly checking the whitelist or ECS security group rules and forbidding unauthorized CIDR blocks, or connecting the database to DTS by using Express Connect, VPN Gateway, or Smart Access Gateway.
-
Configure the synchronization objects and advanced settings.
Parameter
Description
Synchronization Types
DTS always selects Incremental Data Synchronization. By default, you must also select Schema Synchronization and Full Data Synchronization. After the precheck, DTS initializes the destination cluster with the full data of the selected source objects, which serves as the baseline for subsequent incremental synchronization.
Synchronization Topology
Select One-way Synchronization.
Processing Mode of Conflicting Tables
Precheck and Report Errors: Checks if the destination database contains collections with the same names. If a collection with a duplicate name is found, an error is reported during the precheck phase and the data synchronization task does not start. Otherwise, the precheck is successful.
NoteIf you cannot delete or rename the collection with the same name in the destination database, you can use the object name mapping feature to change the collection name in the destination database. For more information, see Set the name of a synchronization object in the destination instance.
Ignore Errors and Proceed: Skips checking for collections with the same name in the destination database.
WarningSelecting Ignore Errors and Proceed may cause data inconsistency and put your business at risk. For example:
If a record in the destination database has the same primary key or unique key value as a record in the source database, the record in the destination database is retained. The record from the source database is not synchronized to the destination database.
Data initialization may fail, only some data may be synchronized, or the synchronization may fail.
Capitalization of Object Names in Destination Instance
Configure the case-sensitivity policy for database, table, and column names in the destination instance. By default, the DTS default policy is selected. You can also choose to use the default policy of the source or destination database. For more information, see Case policy for destination object names.
Source Objects
In the Source Objects box, click the objects, and then click
to move them to the Selected Objects box.NoteSynchronization can be performed at the DATABASE and COLLECTION levels.
Selected Objects
To rename a single object in the destination instance, right-click the object in the Selected Objects box. For more information, see Map a single object name.
To rename multiple objects in bulk, click Batch Edit in the upper-right corner of the Selected Objects box. For more information, see Map multiple object names in bulk.
-
Click Next: Advanced Settings to proceed to the advanced settings.
-
Data Verification Settings
To configure data validation, see Configure data validation.
-
Advanced Settings
Parameter
Description
Dedicated Cluster for Task Scheduling
By default, DTS uses a shared cluster for tasks, so you do not need to make a selection. For greater task stability, you can purchase a dedicated cluster to run the DTS synchronization task. For more information, see What is a DTS dedicated cluster?.
Retry Time for Failed Connections
If the connection to the source or destination database fails after the synchronization task starts, DTS reports an error and immediately begins to retry the connection. The default retry duration is 720 minutes. You can customize the retry time to a value from 10 to 1,440 minutes. We recommend a duration of 30 minutes or more. If the connection is restored within this period, the task resumes automatically. Otherwise, the task fails.
NoteIf multiple DTS instances (e.g., Instance A and B) share a source or destination, DTS uses the shortest configured retry duration (e.g., 30 minutes for A, 60 for B, so 30 minutes is used) for all instances.
DTS charges for task runtime during connection retries. Set a custom duration based on your business needs, or release the DTS instance promptly after you release the source/destination instances.
Retry Time for Other Issues
If a non-connection issue (e.g., a DDL or DML execution error) occurs, DTS reports an error and immediately retries the operation. The default retry duration is 10 minutes. You can also customize the retry time to a value from 1 to 1,440 minutes. We recommend a duration of 10 minutes or more. If the related operations succeed within the set retry time, the synchronization task automatically resumes. Otherwise, the task fails.
ImportantThe value of Retry Time for Other Issues must be less than that of Retry Time for Failed Connections.
Enable Throttling for Full Data Synchronization
During full data synchronization, DTS consumes read and write resources from the source and destination databases, which can increase their load. To mitigate pressure on the destination database, you can limit the migration rate by setting Queries per second (QPS) to the source database, RPS of Full Data Migration, and Data migration speed for full migration (MB/s).
NoteThis parameter is available only if Synchronization Types is set to Full Data Synchronization.
You can also adjust the rate of full data synchronization when the synchronization instance is running.
Enable Throttling for Incremental Data Synchronization
You can also limit the incremental synchronization rate to reduce pressure on the destination database by setting RPS of Incremental Data Synchronization and Data synchronization speed for incremental synchronization (MB/s).
Environment Tag
You can select an environment tag to identify the instance based on your business needs. In this example, you do not need to select a tag.
Configure ETL
Choose whether to enable the extract, transform, and load (ETL) feature. For more information, see What is ETL? Valid values:
-
Yes: Enables the ETL feature. Enter data processing statements in the code editor. For more information, see Configure ETL in a data migration or data synchronization task.
-
No: Disables the ETL feature.
Monitoring and Alerting
Choose whether to set up alerts. If the synchronization fails or the latency exceeds the specified threshold, DTS sends a notification to the alert contacts.
No: No alerts are configured.
Yes: Configures alerts. You must also set the alert threshold and alert notifications. For more information, see Configure monitoring and alerting during task configuration.
-
Save the task and perform a precheck.
To view the parameters for configuring this instance via an API operation, hover over the Next: Save Task Settings and Precheck button and click Preview OpenAPI parameters in the tooltip.
If you have finished viewing the API parameters, click Next: Save Task Settings and Precheck at the bottom of the page.
NoteBefore a synchronization task starts, DTS performs a precheck. You can start the task only if the precheck passes.
If the precheck fails, click View Details next to the failed item, fix the issue as prompted, and then rerun the precheck.
If the precheck generates warnings:
For non-ignorable warning, click View Details next to the item, fix the issue as prompted, and run the precheck again.
For ignorable warnings, you can bypass them by clicking Confirm Alert Details, then Ignore, and then OK. Finally, click Precheck Again to skip the warning and run the precheck again. Ignoring precheck warnings may lead to data inconsistencies and other business risks. Proceed with caution.
When the Success Rate reaches 100%, click Next: Purchase Instance.
On the Purchase page, select the billing method and link specifications for the data synchronization instance. For more information, see the following table.
Category
Parameter
Description
New Instance Class
Billing Method
Subscription: You pay upfront for a specific duration. This is cost-effective for long-term, continuous tasks.
Pay-as-you-go: You are billed hourly for actual usage. This is ideal for short-term or test tasks, as you can release the instance at any time to save costs.
Resource Group Settings
The resource group to which the instance belongs. The default is default resource group. For more information, see What is Resource Management?.
Instance Class
DTS offers synchronization specifications at different performance levels that affect the synchronization rate. Select a specification based on your business requirements. For more information, see Data synchronization link specifications.
Subscription Duration
In subscription mode, select the duration and quantity of the instance. Monthly options range from 1 to 9 months. Yearly options include 1, 2, 3, or 5 years.
NoteThis option appears only when the billing method is Subscription.
Read and select the checkbox for Data Transmission Service (Pay-as-you-go) Service Terms.
Click Buy and Start, and then click OK in the OK dialog box.
You can monitor the task progress on the data synchronization page.