mongodb - 复制/克隆 mongodb 数据库及其数据

我需要复制我的 Mongo 数据库及其数据。我试过了

db.copyDatabase( "Old_db", "new_db", "localhost" )

但问题是它只复制一个空白数据库,而不是以前的数据。

最佳答案

2019 年 2 月

自从 db.copyDatabase()在 v4.0 中已弃用,您应该使用 mongodumpmongorestore而是:

mongodump 
    --host <source host:port> 
    --ssl 
    --username <username> 
    --password <password> 
    --authenticationDatabase admin 
    --db <sourceDbName> 
    --collection <collection-name>

mongodump命令会将整个数据库导出到名为 dump/<sourceDbName> 的本地文件夹中。默认情况下,然后使用 mongorestore导入目标数据库的命令:

mongorestore 
    --host <target host:port> 
    --ssl 
    --username <username> 
    --password <password> 
    --authenticationDatabase admin 
    --db <targetDbName>
    --collection <collection-name>
    <dump folder/file>

例子:

# backup the whole db (mydb-old):
mongodump -h Cluster0-shard-0/sample-shard-00-00-xyz.mongodb.net:27017 \
--ssl -u user1 -p 123123 --authenticationDatabase admin \
-d mydb-old

# backup only one collection (mydb-old.users):
mongodump -h Cluster0-shard-0/sample-shard-00-00-xyz.mongodb.net:27017 \
--ssl -u user1 -p 123123 --authenticationDatabase admin \
-d mydb-old -c users

# restore the whole db (mydb-old) to mydb-new:
mongorestore -h Cluster0-shard-0/sample-shard-00-00-xyz.mongodb.net:27017 \
--ssl -u user1 -p 123123 --authenticationDatabase admin \
-d mydb-new dump/mydb-old

# restore only one collection (mydb-old.users) to mydb-new.users:
mongorestore -h Cluster0-shard-0/sample-shard-00-00-xyz.mongodb.net:27017 \
--ssl -u user1 -p 123123 --authenticationDatabase admin \
-d mydb-new -c users dump/mydb-old/users.bson

了解更多:

  • mongodump
  • mongorestore

https://stackoverflow.com/questions/14846712/

相关文章:

javascript - Mongoose - RangeError : Maximum Call

mongodb - 在 MongoDB 中,如果删除了集合,索引也会自动删除吗?

mongodb - 使用 apt-get 安装 mongodb-10gen 失败

mongodb - 如何将 mongodb 数据库转移到另一台看不到第一个的机器上

mongodb - 无法启动mongodb服务

javascript - MongoDB mongoose 弃用警告

c# - MongoDB C# Driver 2.0 - 更新文档

mongodb - 更新 Mongodb 中的嵌入文档属性

javascript - 如何在 MongoDB 中对集合记录中的数组进行排序?

mongodb - 奇怪的 mongodb 和 mongoose 错误 : not master a