MongoDB Migration Methods
MongoDB offers several migration approaches depending on your downtime tolerance and data size. This guide covers mongodump/mongorestore for small databases, replica set migration for zero downtime, and live sync for large datasets.
Method 1: mongodump and mongorestore
# Export from source server
mongodump --host source-server --port 27017 \
--username admin --password secret \
--authenticationDatabase admin \
--out /backup/mongo-dump \
--gzip
# Transfer to destination
rsync -avz /backup/mongo-dump/ user@dest-server:/tmp/mongo-dump/
# Import on destination
mongorestore --host localhost --port 27017 \
--username admin --password new_secret \
--authenticationDatabase admin \
/tmp/mongo-dump/ --gzip
# For specific database only:
mongodump --db myapp --gzip --archive=myapp.gz
mongorestore --gzip --archive=myapp.gz
Method 2: Replica Set for Zero Downtime
# 1. Add new server to existing replica set
# On primary, add new member:
rs.add("new-server:27017")
# 2. Wait for initial sync to complete
rs.status()
# Check new member state is SECONDARY
# 3. Step down primary to trigger election
rs.stepDown()
# 4. Remove old members from replica set
rs.remove("old-server:27017")
# 5. Update application connection strings
Method 3: Live Sync with mongosync
# For MongoDB 6.0+ with mongosync
mongosync --cluster0 "mongodb://source:27017" \
--cluster1 "mongodb://dest:27017"
# mongosync handles continuous replication
# When ready, commit the migration:
curl -X POST http://localhost:27182/api/v1/commit
Post-Migration Verification
# Compare document counts
mongo source-server --eval "db.getSiblingDB('myapp').getCollectionNames().forEach(function(c) { print(c + ': ' + db.getSiblingDB('myapp').getCollection(c).countDocuments({})); })"
# Compare on destination and verify counts match
# Test application connectivity
# Update connection strings in all apps
Best Practices
- Always test migration on a staging environment first
- Use --oplog flag with mongodump for point-in-time consistency
- For large databases (100GB+), prefer replica set or mongosync approach
- Verify indexes are recreated on the destination
- Update authentication credentials on the new server