如何将数据库从一个MongoDB服务器复制到另一个服务器?

时间:2011-03-31 03:51:46

标签: mongodb

我在不同的服务器上有两个mongodbs,都以--auth开头。现在我想将数据库从一台服务器复制到另一台服务器。

> mongo
> use admin
> db.copyDatabase("mydb","mydb","another_server")

它显示:

{ "errmsg" : "", "ok" : 0 }

> db.getLastError()
null

似乎没有错误,但副本不成功。什么是正确的命令?

5 个答案:

答案 0 :(得分:82)

如果您使用 - auth ,则需要在其中包含您的用户名/密码...

运行命令时,必须在“目标”服务器上。

db.copyDatabase(<from_db>, <to_db>, <from_hostname>, <username>, <password>);

如果所有这些都不起作用,您可能想要尝试创建要复制的数据库的从属...

答案 1 :(得分:25)

Mongo版本3.2开始,您可以使用mongodump/mongorestore执行此操作:

mongodump  --host <from_host> --db <from_db> --archive | mongorestore --host <to_host> --archive

可在以下网址找到更多信息:

https://docs.mongodb.com/manual/reference/program/mongodump/ https://docs.mongodb.com/manual/reference/program/mongorestore/

要使远程mongo可达,您可以创建ssh隧道:

ssh -fN -L 27017:localhost:27117 <remote_host> 

在这种情况下,命令可以是:

mongodump  --port 27117 --db <from_db> --archive | mongorestore --archive

答案 2 :(得分:22)

除了Justin Jenkins的答案之外,请记住,如果你没有mongodb暴露在网络中,你也可以使用ssh隧道(仅限localhost)

我使用屏幕在“任务”之间切换。为方便起见,ssh隧道和mongo在单独的屏幕选项卡中执行。

第1步:创建隧道

ssh username@yourdomainOrIP -L 27018:localhost:27017
...Enter your password

第2步:

mongo
use admin
db.copyDatabase(<fromdb>,<todb>,"localhost:27018",<username>,<password)

答案 3 :(得分:1)

除了Mike Shauneu的答案外,如果目标服务器上的数据库名称与源服务器上的数据库名称不同,则需要重写名称空间。结合身份验证,我可以使用--uri选项来实现此功能,该选项需要最新的mongo版本(> 3.4.6):

mongodump --uri="mongodb://$sourceUser:$sourcePwd@$sourceHost/$sourceDb" --gzip --archive | mongorestore --uri="mongodb://$targetUser:$targetPwd@$targetHost/$targetDb" --nsFrom="$sourceDb.*" --nsTo="$targetDb.*" --gzip --archive

答案 4 :(得分:0)

以下内容对我有用,可以将它们从Ubuntu Server复制到另一个都运行MongoDB v4 +的Ubuntu Server:

  1. 以下命令应从要还原数据库的服务器上执行:
   ssh -fN -L 27018:127.0.0.1:27017 <remote_host_ip>
  1. 现在,我们已将远程服务器数据库映射到本地服务器端口27018。接下来,我们可以使用MongoDB的mongodump/mongorestore管道从远程服务器复制到目标服务器:
   mongodump --port 27018 --db <remote_db_name> --username <remote_db_username> --password <remote_db_password> --archive | mongorestore --username <destination_db_username> --password <destination_db_password> --archive
  1. [可选]您可以按以下方式检查恢复的数据库:
   mongo --authenticationDatabase "admin" -u <destination_db_username> -p
   show dbs

检查您的数据库是否存在于列表中。

相关问题