mongodb database backup and restore commands

First, mongodb database backup data:
1. Common commands:
mongodump -h IP --port port -u username -p password -d database -o file exists path
If there is no user who, you can remove -u and -p.
If you export the local database, you can remove -h.
If it is the default port, you can remove --port.
If you want to export all databases, you can remove -d.
2, export all databases
mongodump -h 127.0.0.1 -o /home/zhangy/mongodb/
3, export the specified database
mongodump -h 192.168.1.108 -d tank -o /home/zhangy/mongodb/


Second, mongodb restore the database:
1, common command format
mongorestore -h IP --port port -u username -p password -d database --drop file path
--drop means, first delete all records, and then restore.
2, restore all databases to mongodb
mongorestore /home/zhangy/mongodb/
3, restore the specified database
mongorestore -d tank /home/zhangy/mongodb/tank/ #tank the backup path of this database
mongorestore -d tank_new /home/zhangy/mongodb/tank/ #Restore tank to tank_new database
These two commands can realize database backup and restore, and the file formats are json and bson. Cannot refer to write-to-table backup or restore.


three, mongoexport exports a table, or some fields in a table
1, common command format
mongoexport -h IP --port port -u username -p password -d database -c table name -f field -q conditional export --csv -o filename
-f Export refers to the field, separated by font size, -f name, email, age export the three fields of name, email, age
-q    可以根查询条件导出,-q '{ "uid" : "100" }' 导出uid为100的数据
--csv 表示导出的文件格式为csv的,这个比较有用,因为大部分的关系型数据库都是支持csv,在这里有共同点
2,导出整张表
mongoexport -d tank -c users -o /home/zhangy/mongodb/tank/users.dat
3,导出表中部分字段
mongoexport -d tank -c users --csv -f uid,name,sex -o tank/users.csv
4,根据条件敢出数据
mongoexport -d tank -c users -q '{uid:{$gt:1}}' -o tank/users.json


四、mongoimport导入表,或者表中部分字段
1,常用命令格式
1.1,还原整表导出的非csv文件
mongoimport -h IP --port 端口 -u 用户名 -p 密码 -d 数据库 -c 表名 --upsert --drop 文件名  
重点说一下--upsert,其他参数上面的命令已有提到,--upsert 插入或者更新现有数据
1.2,还原部分字段的导出文件
mongoimport -h IP --port 端口 -u 用户名 -p 密码 -d 数据库 -c 表名 --upsertFields 字段 --drop 文件名  
--upsertFields根--upsert一样
1.3,还原导出的csv文件
mongoimport -h IP --port 端口 -u 用户名 -p 密码 -d 数据库 -c 表名 --type 类型 --headerline --upsert --drop 文件名  
2,还原导出的表数据
mongoimport -d tank -c users --upsert tank/users.dat
3,部分字段的表数据导入
mongoimport -d tank -c users  --upsertFields uid,name,sex  tank/users.dat  
4,还原csv文件
mongoimport -d tank -c users --type csv --headerline --file tank/users.csv

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324582552&siteId=291194637