MongoDB备份、还原、导出、导入、克隆操作示例

数据库备份 – mongodump

备份本地所有MongoDB数据库:

# mongodump -h 127.0.0.1 --port 27017 -o /root/db/alldb

备份远程指定数据库:
# mongodump -h 192.168.1.233 --port 27018 -d yourdb -o /root/db/yourdb

更多mongodump详解

数据库还原-mongorestore

恢复所有数据库到MongoDB中:

# mongorestore -h 127.0.0.1 --port 27018 /root/db/alldb

还原指定数据库:
# mongorestore --port 27017 -d yourdb /root/db/yourdb

更多mongorestore详解
导出集合数据-mongoexport

导出数据库中指定集合的数据:

# mongoexport -h 192.168.1.233 --port 27018 -d yourdb -c yourcoll -o /root/yourcoll.json

导出集合中指定字段的数据,导出的文件格式为csv:
# mongoexport -d yourdb -c test -f "id,name,score" --csv -o /root/test.csv

根据条件导出数据:
# mongoexport -d yourdb -c yourcoll -q '{score:{$gt:80}}' -o /root/yourcoll-bk.json

更多mongoexport详解

集合数据导入-mongoimport

还原导出的集合数据:

# mongoimport -d yourdb -c yourcoll --file /root/yourcoll.json

导入集合数据,插入或更新现有的数据:
# mongoimport -d test -c yourcoll --file /root/yourcoll.json --upsert

更多mongoimport详解

MongoDB数据库克隆

命令格式:

db.copyDatabase(fromdb, todb, fromhost, username, password)

从远程MongoDB中复制指定数据库到本地:
# mongo
> db.copyDatabase("yii2", "lyii2", "192.168.0.69")

更多db.copyDatabase详解
集合的克隆

命令格式:

db.runCommand({ cloneCollection: "<namespace>", from: "<hostname>", query: { <query> } });

从远程MongoDB中克隆指定的集合到本地数据库中:
# mongo
> db.runCommand({  cloneCollection: "test.user", from: "192.168.0.69", query:{}    })

更多cloneCollection详解