引言
在现代应用开发中,数据库迁移是不可避免的环节。无论是从本地环境迁移到云环境、从单节点迁移到集群、还是从旧版本升级到新版本,MongoDB作为流行的NoSQL数据库,其迁移过程需要谨慎规划和执行。本文将详细介绍MongoDB数据库迁移的常用工具、实战步骤以及最佳实践,帮助您实现数据无缝迁移与高效管理。
一、MongoDB迁移的常见场景
1.1 环境迁移
本地到云
:将本地部署的MongoDB迁移到云服务(如MongoDB Atlas、AWS DocumentDB等)
云到本地
:将云数据库迁回本地环境
跨云迁移
:从一个云服务商迁移到另一个云服务商
1.2 架构迁移
单节点到副本集
:从单节点部署迁移到高可用的副本集架构
副本集到分片集群
:从副本集迁移到分片集群以支持更大规模数据
版本升级
:从旧版本MongoDB升级到新版本
1.3 数据迁移
数据合并
:将多个数据库或集合的数据合并到一个目标数据库
数据清理
:在迁移过程中进行数据清洗和转换
数据同步
:保持源和目标数据库之间的实时同步
二、MongoDB迁移工具推荐
2.1 MongoDB官方工具
2.1.1 mongodump 和 mongorestore
适用场景
:备份恢复、全量迁移、离线迁移
特点
:
MongoDB官方提供的命令行工具
支持全量备份和恢复
支持按数据库、集合进行备份
支持压缩和加密
实战示例
:
# 备份整个数据库
mongodump –host localhost –port 27017 –db mydb –out /backup/mongodb
# 恢复数据库
mongorestore –host localhost –port 27017 –db mydb /backup/mongodb/mydb
# 备份特定集合
mongodump –host localhost –port 27017 –db mydb –collection users –out /backup/mongodb
# 使用压缩备份
mongodump –host localhost –port 27017 –db mydb –gzip –out /backup/mongodb
# 恢复压缩备份
mongorestore –host localhost –port 27017 –db mydb –gzip /backup/mongodb/mydb.bson.gz
2.1.2 mongoexport 和 mongoimport
适用场景
:数据导出导入、格式转换、小规模数据迁移
特点
:
支持JSON和CSV格式
适合小规模数据迁移
可以进行字段映射和转换
实战示例
:
# 导出为JSON格式
mongoexport –host localhost –port 27017 –db mydb –collection users –out users.json
# 导出为CSV格式
mongoexport –host localhost –port 27017 –db mydb –collection users –type=csv –fields=_id,name,email –out users.csv
# 导入JSON数据
mongoimport –host localhost –port 27017 –db mydb –collection users –file users.json
# 导入CSV数据
mongoimport –host localhost –port 27017 –db mydb –collection users –type=csv –headerline –file users.csv
2.1.3 MongoDB Compass
适用场景
:可视化迁移、数据探索、小规模数据操作
特点
:
MongoDB官方GUI工具
支持拖拽式数据迁移
提供数据可视化和查询功能
适合非技术人员使用
2.2 第三方迁移工具
2.2.1 Studio 3T
适用场景
:企业级迁移、复杂数据转换、团队协作
特点
:
强大的可视化界面
支持SQL查询MongoDB
数据导入导出功能
数据比较和同步功能
实战示例
:
连接源数据库和目标数据库
选择要迁移的集合
配置字段映射和转换规则
执行迁移任务
监控迁移进度
2.2.2 Navicat for MongoDB
适用场景
:数据库管理、数据迁移、日常维护
特点
:
直观的图形界面
支持多种数据格式
数据同步功能
调度任务功能
2.2.3 MongoDB Atlas Live Migration
适用场景
:迁移到MongoDB Atlas云服务
特点
:
MongoDB官方提供的迁移服务
支持零停机迁移
自动化迁移流程
适用于生产环境
2.3 自定义迁移脚本
2.3.1 使用Node.js和MongoDB驱动
适用场景
:复杂业务逻辑迁移、数据转换、增量迁移
特点
:
灵活性高,可定制性强
支持复杂业务逻辑
可以实现增量迁移
适合开发团队使用
实战示例
:
const { MongoClient } = require(‘mongodb’);
async function migrateData() {
// 连接源数据库
const sourceClient = new MongoClient(‘mongodb://localhost:27017’);
await sourceClient.connect();
const sourceDb = sourceClient.db(‘mydb’);
// 连接目标数据库
const targetClient = new MongoClient(‘mongodb://target-host:27017’);
await targetClient.connect();
const targetDb = targetClient.db(‘mydb’);
try {
// 获取源集合
const sourceCollection = sourceDb.collection(‘users’);
const targetCollection = targetDb.collection(‘users’);
// 读取数据并迁移
const cursor = sourceCollection.find({});
let batch = [];
const batchSize = 1000;
for await (const doc of cursor) {
// 数据转换逻辑
const transformedDoc = {
…doc,
migratedAt: new Date(),
status: ‘active’
};
batch.push(transformedDoc);
// 批量写入
if (batch.length >= batchSize) {
await targetCollection.insertMany(batch);
console.log(`Migrated ${batch.length} documents`);
batch = [];
}
}
// 写入剩余数据
if (batch.length > 0) {
await targetCollection.insertMany(batch);
console.log(`Migrated final ${batch.length} documents`);
}
console.log(‘Migration completed successfully’);
} catch (error) {
console.error(‘Migration failed:’, error);
} finally {
await sourceClient.close();
await targetClient.close();
}
}
migrateData();
2.3.2 使用Python和PyMongo
适用场景
:数据分析、ETL流程、科学计算
特点
:
Python生态系统丰富
适合数据科学团队
支持复杂数据处理
实战示例
:
from pymongo import MongoClient
import pandas as pd
from datetime import datetime
def migrate_data():
# 连接源数据库
source_client = MongoClient(‘mongodb://localhost:27017’)
source_db = source_client[‘mydb’]
# 连接目标数据库
target_client = MongoClient(‘mongodb://target-host:27017’)
target_db = target_client[‘mydb’]
try:
# 获取源集合
source_collection = source_db[‘users’]
target_collection = target_db[‘users’]
# 读取数据
cursor = source_collection.find({})
# 转换为DataFrame进行处理
df = pd.DataFrame(list(cursor))
# 数据清洗和转换
df[‘migrated_at’] = datetime.now()
df[‘status’] = ‘active’
# 转换为字典列表
records = df.to_dict(‘records’)
# 批量插入
if records:
target_collection.insert_many(records)
print(f”Migrated {len(records)} documents”)
print(“Migration completed successfully”)
except Exception as e:
print(f”Migration failed: {e}”)
finally:
source_client.close()
target_client.close()
if __name__ == “__main__”:
migrate_data()
三、MongoDB迁移实战指南
3.1 迁移前准备
3.1.1 环境评估
数据量评估
:
使用
db.stats()
和
db.collection.stats()
评估数据大小
估算迁移时间:通常1GB数据需要10-30分钟
网络带宽评估
:
测试源和目标之间的网络延迟和带宽
计算迁移所需时间
版本兼容性检查
:
检查源和目标MongoDB版本
参考MongoDB官方兼容性文档
3.1.2 备份策略
# 创建完整备份
mongodump –host source-host –port 27017 –out /backup/mongodb-$(date +%Y%m%d)
# 验证备份完整性
mongorestore –host test-host –port 27017 –db testdb /backup/mongodb-20231201/mydb –dryRun
3.1.3 迁移计划制定
确定迁移时间窗口
:选择业务低峰期
制定回滚方案
:准备快速回滚的脚本
通知相关方
:提前通知开发、运维、业务团队
3.2 全量迁移实战
3.2.1 使用mongodump/mongorestore
步骤
:
停止应用写入
(如果可能)
执行备份
传输备份文件
恢复数据
验证数据完整性
切换应用连接
完整脚本示例
:
#!/bin/bash
# MongoDB全量迁移脚本
# 配置变量
SOURCE_HOST=”source-host”
SOURCE_PORT=27017
TARGET_HOST=”target-host”
TARGET_PORT=27017
BACKUP_DIR=”/backup/mongodb”
DB_NAME=”mydb”
# 1. 创建备份目录
mkdir -p $BACKUP_DIR
# 2. 执行备份
echo “开始备份…”
mongodump –host $SOURCE_HOST –port $SOURCE_PORT –db $DB_NAME –out $BACKUP_DIR
if [ $? -ne 0 ]; then
echo “备份失败!”
exit 1
fi
# 3. 压缩备份文件
echo “压缩备份文件…”
tar -czf $BACKUP_DIR.tar.gz -C $BACKUP_DIR .
if [ $? -ne 0 ]; then
echo “压缩失败!”
exit 1
fi
# 4. 传输备份文件(如果需要)
echo “传输备份文件…”
# scp $BACKUP_DIR.tar.gz target-host:/tmp/
# 5. 恢复数据
echo “开始恢复数据…”
mongorestore –host $TARGET_HOST –port $TARGET_PORT –db $DB_NAME $BACKUP_DIR/$DB_NAME
if [ $? -ne 0 ]; then
echo “恢复失败!”
exit 1
fi
# 6. 验证数据
echo “验证数据…”
mongosh –host $TARGET_HOST –port $TARGET_PORT –eval “db.getSiblingDB(‘$DB_NAME’).stats()”
echo “迁移完成!”
3.2.2 使用自定义脚本迁移
场景
:需要数据转换、过滤或增量迁移
步骤
:
设计数据转换逻辑
实现迁移脚本
测试迁移过程
执行迁移
验证结果
完整示例
:
// MongoDB数据迁移脚本(支持增量迁移)
const { MongoClient } = require(‘mongodb’);
class MongoDBMigrator {
constructor(sourceConfig, targetConfig) {
this.sourceConfig = sourceConfig;
this.targetConfig = targetConfig;
this.migrationState = {
lastMigratedId: null,
migratedCount: 0,
startTime: null,
endTime: null
};
}
async connect() {
this.sourceClient = new MongoClient(this.sourceConfig.uri);
this.targetClient = new MongoClient(this.targetConfig.uri);
await this.sourceClient.connect();
await this.targetClient.connect();
this.sourceDb = this.sourceClient.db(this.sourceConfig.db);
this.targetDb = this.targetClient.db(this.targetConfig.db);
}
async migrateCollection(collectionName, transformFn = null) {
console.log(`开始迁移集合: ${collectionName}`);
const sourceCollection = this.sourceDb.collection(collectionName);
const targetCollection = this.targetDb.collection(collectionName);
// 获取迁移状态
const state = await this.getMigrationState(collectionName);
this.migrationState.lastMigratedId = state.lastMigratedId;
// 构建查询条件
const query = state.lastMigratedId ?
{ _id: { $gt: state.lastMigratedId } } : {};
const cursor = sourceCollection.find(query).sort({ _id: 1 });
let batch = [];
const batchSize = 1000;
for await (const doc of cursor) {
// 数据转换
let transformedDoc = transformFn ? transformFn(doc) : doc;
// 添加迁移标记
transformedDoc._migrated = true;
transformedDoc._migratedAt = new Date();
batch.push(transformedDoc);
// 批量写入
if (batch.length >= batchSize) {
await this.writeBatch(targetCollection, batch);
this.migrationState.migratedCount += batch.length;
this.migrationState.lastMigratedId = batch[batch.length – 1]._id;
// 保存迁移状态
await this.saveMigrationState(collectionName);
console.log(`已迁移: ${this.migrationState.migratedCount} 条记录`);
batch = [];
}
}
// 写入剩余数据
if (batch.length > 0) {
await this.writeBatch(targetCollection, batch);
this.migrationState.migratedCount += batch.length;
this.migrationState.lastMigratedId = batch[batch.length – 1]._id;
await this.saveMigrationState(collectionName);
}
console.log(`集合 ${collectionName} 迁移完成,共迁移 ${this.migrationState.migratedCount} 条记录`);
}
async writeBatch(collection, batch) {
try {
await collection.insertMany(batch, { ordered: false });
} catch (error) {
// 处理重复键错误
if (error.code === 11000) {
console.log(‘检测到重复键,尝试逐条插入…’);
for (const doc of batch) {
try {
await collection.insertOne(doc);
} catch (e) {
if (e.code !== 11000) {
throw e;
}
}
}
} else {
throw error;
}
}
}
async getMigrationState(collectionName) {
const stateCollection = this.targetDb.collection(‘_migration_state’);
const state = await stateCollection.findOne({ collection: collectionName });
return state || { lastMigratedId: null, migratedCount: 0 };
}
async saveMigrationState(collectionName) {
const stateCollection = this.targetDb.collection(‘_migration_state’);
await stateCollection.updateOne(
{ collection: collectionName },
{
$set: {
lastMigratedId: this.migrationState.lastMigratedId,
migratedCount: this.migrationState.migratedCount,
updatedAt: new Date()
}
},
{ upsert: true }
);
}
async close() {
await this.sourceClient.close();
await this.targetClient.close();
}
}
// 使用示例
async function main() {
const migrator = new MongoDBMigrator(
{ uri: ‘mongodb://source-host:27017’, db: ‘mydb’ },
{ uri: ‘mongodb://target-host:27017’, db: ‘mydb’ }
);
try {
await migrator.connect();
// 迁移users集合,添加转换逻辑
await migrator.migrateCollection(‘users’, (doc) => {
// 示例:添加默认值、格式化字段
return {
…doc,
status: doc.status || ‘active’,
lastLogin: doc.lastLogin || new Date(),
profile: {
…doc.profile,
updatedAt: new Date()
}
};
});
// 迁移orders集合
await migrator.migrateCollection(‘orders’);
} catch (error) {
console.error(‘迁移失败:’, error);
} finally {
await migrator.close();
}
}
main();
3.3 增量迁移实战
3.3.1 基于时间戳的增量迁移
适用场景
:需要保持源和目标数据同步
实现方案
:
在源数据中添加时间戳字段
记录每次迁移的最后时间戳
定期同步新数据
代码示例
:
// 增量迁移脚本
const { MongoClient } = require(‘mongodb’);
const fs = require(‘fs’);
class IncrementalMigrator {
constructor(sourceUri, targetUri, dbName) {
this.sourceUri = sourceUri;
this.targetUri = targetUri;
this.dbName = dbName;
this.stateFile = ‘./migration_state.json’;
}
async loadState() {
try {
const data = fs.readFileSync(this.stateFile, ‘utf8’);
return JSON.parse(data);
} catch (error) {
return { lastSyncTime: null, collections: {} };
}
}
async saveState(state) {
fs.writeFileSync(this.stateFile, JSON.stringify(state, null, 2));
}
async migrateIncremental() {
const sourceClient = new MongoClient(this.sourceUri);
const targetClient = new MongoClient(this.targetUri);
try {
await sourceClient.connect();
await targetClient.connect();
const sourceDb = sourceClient.db(this.dbName);
const targetDb = targetClient.db(this.dbName);
const state = await this.loadState();
const now = new Date();
// 获取所有集合
const collections = await sourceDb.listCollections().toArray();
for (const coll of collections) {
const collectionName = coll.name;
if (collectionName.startsWith(‘_’)) continue; // 跳过系统集合
const sourceCollection = sourceDb.collection(collectionName);
const targetCollection = targetDb.collection(collectionName);
// 构建查询条件
const query = {};
if (state.collections[collectionName]?.lastSyncTime) {
query.updatedAt = {
$gt: new Date(state.collections[collectionName].lastSyncTime)
};
}
// 获取增量数据
const cursor = sourceCollection.find(query);
const newDocs = await cursor.toArray();
if (newDocs.length > 0) {
console.log(`发现 ${newDocs.length} 条新记录在 ${collectionName}`);
// 批量更新或插入
for (const doc of newDocs) {
await targetCollection.updateOne(
{ _id: doc._id },
{ $set: doc },
{ upsert: true }
);
}
// 更新状态
if (!state.collections[collectionName]) {
state.collections[collectionName] = {};
}
state.collections[collectionName].lastSyncTime = now.toISOString();
state.collections[collectionName].syncedCount =
(state.collections[collectionName].syncedCount || 0) + newDocs.length;
}
}
state.lastSyncTime = now.toISOString();
await this.saveState(state);
console.log(`增量同步完成,时间: ${now.toISOString()}`);
} finally {
await sourceClient.close();
await targetClient.close();
}
}
}
// 定时执行增量迁移
async function runScheduledMigration() {
const migrator = new IncrementalMigrator(
‘mongodb://source-host:27017’,
‘mongodb://target-host:27017’,
‘mydb’
);
try {
await migrator.migrateIncremental();
} catch (error) {
console.error(‘增量迁移失败:’, error);
}
}
// 每5分钟执行一次
setInterval(runScheduledMigration, 5 * 60 * 1000);
3.3.2 使用Change Streams实现实时同步
适用场景
:需要近乎实时的数据同步
代码示例
:
const { MongoClient } = require(‘mongodb’);
class ChangeStreamMigrator {
constructor(sourceUri, targetUri, dbName) {
this.sourceUri = sourceUri;
this.targetUri = targetUri;
this.dbName = dbName;
this.changeStream = null;
}
async startRealTimeSync() {
const sourceClient = new MongoClient(this.sourceUri);
const targetClient = new MongoClient(this.targetUri);
try {
await sourceClient.connect();
await targetClient.connect();
const sourceDb = sourceClient.db(this.dbName);
const targetDb = targetClient.db(this.dbName);
// 监听所有集合的变化
const collections = await sourceDb.listCollections().toArray();
for (const coll of collections) {
const collectionName = coll.name;
if (collectionName.startsWith(‘_’)) continue;
const sourceCollection = sourceDb.collection(collectionName);
const targetCollection = targetDb.collection(collectionName);
// 创建Change Stream
const stream = sourceCollection.watch([
{ $match: { operationType: { $in: [‘insert’, ‘update’, ‘delete’] } } }
]);
stream.on(‘change’, async (change) => {
try {
switch (change.operationType) {
case ‘insert’:
await targetCollection.insertOne(change.fullDocument);
console.log(`插入: ${collectionName} – ${change.documentKey._id}`);
break;
case ‘update’:
await targetCollection.updateOne(
{ _id: change.documentKey._id },
{ $set: change.updateDescription.updatedFields }
);
console.log(`更新: ${collectionName} – ${change.documentKey._id}`);
break;
case ‘delete’:
await targetCollection.deleteOne({ _id: change.documentKey._id });
console.log(`删除: ${collectionName} – ${change.documentKey._id}`);
break;
}
} catch (error) {
console.error(`处理变更失败: ${error.message}`);
}
});
this.changeStream = stream;
}
console.log(‘实时同步已启动’);
} catch (error) {
console.error(‘启动实时同步失败:’, error);
}
}
async stopRealTimeSync() {
if (this.changeStream) {
await this.changeStream.close();
console.log(‘实时同步已停止’);
}
}
}
// 使用示例
const migrator = new ChangeStreamMigrator(
‘mongodb://source-host:27017’,
‘mongodb://target-host:27017’,
‘mydb’
);
// 启动实时同步
migrator.startRealTimeSync();
// 优雅关闭
process.on(‘SIGINT’, async () => {
await migrator.stopRealTimeSync();
process.exit(0);
});
3.4 迁移验证与测试
3.4.1 数据完整性验证
// 数据完整性验证脚本
const { MongoClient } = require(‘mongodb’);
async function validateMigration(sourceUri, targetUri, dbName) {
const sourceClient = new MongoClient(sourceUri);
const targetClient = new MongoClient(targetUri);
try {
await sourceClient.connect();
await targetClient.connect();
const sourceDb = sourceClient.db(dbName);
const targetDb = targetClient.db(dbName);
const collections = await sourceDb.listCollections().toArray();
let totalErrors = 0;
for (const coll of collections) {
const collectionName = coll.name;
if (collectionName.startsWith(‘_’)) continue;
console.log(`验证集合: ${collectionName}`);
const sourceCollection = sourceDb.collection(collectionName);
const targetCollection = targetDb.collection(collectionName);
// 1. 记录数验证
const sourceCount = await sourceCollection.countDocuments();
const targetCount = await targetCollection.countDocuments();
if (sourceCount !== targetCount) {
console.error(`❌ 记录数不匹配: 源=${sourceCount}, 目标=${targetCount}`);
totalErrors++;
} else {
console.log(`✅ 记录数匹配: ${sourceCount}`);
}
// 2. 随机抽样验证
const sampleSize = Math.min(100, sourceCount);
const sampleCursor = sourceCollection.aggregate([
{ $sample: { size: sampleSize } }
]);
let sampleErrors = 0;
for await (const sourceDoc of sampleCursor) {
const targetDoc = await targetCollection.findOne({ _id: sourceDoc._id });
if (!targetDoc) {
console.error(`❌ 文档缺失: ${sourceDoc._id}`);
sampleErrors++;
continue;
}
// 深度比较(排除迁移标记)
const { _migrated, _migratedAt, …sourceClean } = sourceDoc;
const { _migrated, _migratedAt, …targetClean } = targetDoc;
const sourceStr = JSON.stringify(sourceClean, Object.keys(sourceClean).sort());
const targetStr = JSON.stringify(targetClean, Object.keys(targetClean).sort());
if (sourceStr !== targetStr) {
console.error(`❌ 文档内容不匹配: ${sourceDoc._id}`);
console.error(‘源:’, sourceStr);
console.error(‘目标:’, targetStr);
sampleErrors++;
}
}
if (sampleErrors > 0) {
console.error(`❌ 抽样验证失败: ${sampleErrors}/${sampleSize}`);
totalErrors += sampleErrors;
} else {
console.log(`✅ 抽样验证通过: ${sampleSize}个样本`);
}
// 3. 索引验证
const sourceIndexes = await sourceCollection.indexes();
const targetIndexes = await targetCollection.indexes();
if (sourceIndexes.length !== targetIndexes.length) {
console.error(`❌ 索引数量不匹配: 源=${sourceIndexes.length}, 目标=${targetIndexes.length}`);
totalErrors++;
} else {
console.log(`✅ 索引数量匹配: ${sourceIndexes.length}`);
}
}
if (totalErrors === 0) {
console.log(‘\n🎉 迁移验证通过!所有数据完整无误。’);
} else {
console.error(`\n⚠️ 发现 ${totalErrors} 个错误,请检查迁移过程。`);
}
} finally {
await sourceClient.close();
await targetClient.close();
}
}
// 使用示例
validateMigration(
‘mongodb://source-host:27017’,
‘mongodb://target-host:27017’,
‘mydb’
);
3.4.2 性能测试
# 使用mongoperf测试磁盘I/O性能
mongoperf -f /path/to/mongoperf.json
# mongoperf.json示例
{
“nThreads”: 16,
“fileSizeMB”: 1000,
“storageEngine”: “wiredTiger”,
“syncDelay”: 10,
“doPrealloc”: true,
“journal”: true,
“quiet”: false,
“readPercentage”: 0,
“rps”: 0,
“wps”: 0,
“random”: true
}
# 使用mongostat监控迁移性能
mongostat –host target-host –port 27017 –interval 1
四、迁移最佳实践
4.1 迁移策略选择
迁移场景
推荐工具
优点
缺点
小数据量(<10GB)
mongodump/mongorestore
简单、官方支持
大数据量慢
大数据量(>100GB)
自定义脚本+分片
可控性强、支持增量
开发成本高
实时同步
Change Streams
实时性好
需要持续运行
云迁移
MongoDB Atlas Live Migration
零停机、自动化
仅限Atlas
复杂转换
Studio 3T/自定义脚本
灵活、可视化
商业工具或开发成本
4.2 性能优化技巧
4.2.1 并行处理
// 并行迁移多个集合
async function parallelMigrate(collections, maxParallel = 5) {
const queue = […collections];
const workers = [];
async function worker() {
while (queue.length > 0) {
const collection = queue.shift();
if (!collection) break;
try {
await migrateCollection(collection);
} catch (error) {
console.error(`迁移 ${collection} 失败:`, error);
}
}
}
// 启动多个worker
for (let i = 0; i < maxParallel; i++) {
workers.push(worker());
}
await Promise.all(workers);
}
4.2.2 批量操作优化
// 优化批量插入
async function optimizedBatchInsert(collection, docs, batchSize = 1000) {
const batches = [];
for (let i = 0; i < docs.length; i += batchSize) {
batches.push(docs.slice(i, i + batchSize));
}
// 并行处理批次
const promises = batches.map(batch =>
collection.insertMany(batch, { ordered: false })
.catch(error => {
// 处理重复键等错误
if (error.code === 11000) {
return handleDuplicateKeys(collection, batch);
}
throw error;
})
);
await Promise.all(promises);
}
4.3 错误处理与回滚
4.3.1 错误处理机制
class MigrationErrorHandler {
constructor(maxRetries = 3, retryDelay = 1000) {
this.maxRetries = maxRetries;
this.retryDelay = retryDelay;
this.errorLog = [];
}
async executeWithRetry(operation, context = {}) {
let lastError;
for (let attempt = 1; attempt <= this.maxRetries; attempt++) {
try {
return await operation();
} catch (error) {
lastError = error;
console.error(`尝试 ${attempt} 失败:`, error.message);
// 记录错误
this.errorLog.push({
timestamp: new Date(),
attempt,
error: error.message,
context
});
// 指数退避
if (attempt < this.maxRetries) {
const delay = this.retryDelay * Math.pow(2, attempt - 1);
console.log(`等待 ${delay}ms 后重试...`);
await new Promise(resolve => setTimeout(resolve, delay));
}
}
}
throw lastError;
}
getErrorReport() {
return {
totalErrors: this.errorLog.length,
errors: this.errorLog,
summary: this.errorLog.reduce((acc, curr) => {
acc[curr.error] = (acc[curr.error] || 0) + 1;
return acc;
}, {})
};
}
}
4.3.2 回滚方案
#!/bin/bash
# MongoDB迁移回滚脚本
# 配置
BACKUP_DIR=”/backup/mongodb-20231201″
ROLLBACK_HOST=”source-host”
ROLLBACK_PORT=27017
DB_NAME=”mydb”
# 1. 停止应用写入
echo “停止应用写入…”
# 这里可以调用应用管理接口
# 2. 恢复备份
echo “恢复备份…”
mongorestore –host $ROLLBACK_HOST –port $ROLLBACK_PORT –db $DB_NAME $BACKUP_DIR/$DB_NAME
# 3. 验证恢复
echo “验证恢复…”
mongosh –host $ROLLBACK_HOST –port $ROLLBACK_PORT –eval “db.getSiblingDB(‘$DB_NAME’).stats()”
# 4. 重新启动应用
echo “重新启动应用…”
# 这里可以调用应用管理接口
echo “回滚完成!”
4.4 监控与日志
4.4.1 迁移监控脚本
// 迁移监控脚本
const { MongoClient } = require(‘mongodb’);
const fs = require(‘fs’);
class MigrationMonitor {
constructor(logFile = ‘./migration.log’) {
this.logFile = logFile;
this.metrics = {
startTime: null,
endTime: null,
totalDocuments: 0,
migratedDocuments: 0,
errors: 0,
collections: {}
};
}
log(message, level = ‘INFO’) {
const timestamp = new Date().toISOString();
const logEntry = `[${timestamp}] [${level}] ${message}\n`;
console.log(logEntry.trim());
fs.appendFileSync(this.logFile, logEntry);
}
updateMetrics(collection, count, error = false) {
if (!this.metrics.collections[collection]) {
this.metrics.collections[collection] = {
total: 0,
migrated: 0,
errors: 0
};
}
this.metrics.collections[collection].total += count;
if (error) {
this.metrics.collections[collection].errors++;
this.metrics.errors++;
} else {
this.metrics.collections[collection].migrated += count;
this.metrics.migratedDocuments += count;
}
this.metrics.totalDocuments += count;
}
generateReport() {
const duration = this.metrics.endTime – this.metrics.startTime;
const rate = this.metrics.migratedDocuments / (duration / 1000);
return {
summary: {
startTime: this.metrics.startTime,
endTime: this.metrics.endTime,
duration: `${(duration / 1000).toFixed(2)}s`,
totalDocuments: this.metrics.totalDocuments,
migratedDocuments: this.metrics.migratedDocuments,
errorCount: this.metrics.errors,
successRate: ((this.metrics.migratedDocuments / this.metrics.totalDocuments) * 100).toFixed(2) + ‘%’,
documentsPerSecond: rate.toFixed(2)
},
collections: this.metrics.collections
};
}
saveReport(filename = ‘./migration_report.json’) {
const report = this.generateReport();
fs.writeFileSync(filename, JSON.stringify(report, null, 2));
this.log(`报告已保存到 ${filename}`);
}
}
// 使用示例
const monitor = new MigrationMonitor();
monitor.log(‘迁移开始’);
monitor.metrics.startTime = Date.now();
// 在迁移过程中调用
monitor.updateMetrics(‘users’, 1000);
monitor.updateMetrics(‘orders’, 500);
// 迁移结束
monitor.metrics.endTime = Date.now();
monitor.log(‘迁移结束’);
monitor.saveReport();
五、常见问题与解决方案
5.1 迁移速度慢
问题
:大数据量迁移耗时过长
解决方案
:
增加网络带宽
:使用高速网络或专线
并行处理
:同时迁移多个集合
压缩传输
:使用gzip压缩备份文件
分片迁移
:对大数据集合分片处理
5.2 数据不一致
问题
:源和目标数据不一致
解决方案
:
停止写入
:迁移期间停止源数据库写入
使用事务
:在支持事务的版本中使用事务
数据验证
:迁移后进行完整性验证
增量同步
:使用Change Streams保持同步
5.3 版本兼容性问题
问题
:不同版本MongoDB之间的兼容性问题
解决方案
:
查阅官方文档
:MongoDB版本兼容性矩阵
逐步升级
:先升级到中间版本
数据格式转换
:处理不兼容的数据类型
测试验证
:在测试环境充分验证
5.4 网络中断
问题
:迁移过程中网络中断
解决方案
:
断点续传
:实现支持断点续传的迁移脚本
重试机制
:自动重试失败的操作
状态保存
:定期保存迁移状态
监控告警
:设置网络监控和告警
六、总结
MongoDB数据库迁移是一个复杂但可控的过程。通过选择合适的工具、制定详细的计划、实施最佳实践,可以实现数据的无缝迁移和高效管理。关键要点包括:
充分准备
:评估环境、制定计划、创建备份
选择合适工具
:根据场景选择官方工具、第三方工具或自定义脚本
实施最佳实践
:并行处理、批量操作、错误处理
严格验证
:迁移后进行完整性和性能验证
持续监控
:监控迁移过程,及时发现问题
无论是简单的全量迁移还是复杂的实时同步,都有相应的解决方案。通过本文提供的实战指南和代码示例,您可以根据具体需求选择最适合的迁移策略,确保MongoDB数据库迁移的顺利进行。