我想通过命令导出MongoDB中的所有集合:
mongoexport -d dbname -o Mongo.json
结果是: 没有指定集合!
手册说,如果你不指定一个集合,所有的集合都将被导出。 然而,为什么这行不通呢?
http://docs.mongodb.org/manual/reference/mongoexport/#cmdoption-mongoexport--collection
我的MongoDB版本是2.0.6。
我想通过命令导出MongoDB中的所有集合:
mongoexport -d dbname -o Mongo.json
结果是: 没有指定集合!
手册说,如果你不指定一个集合,所有的集合都将被导出。 然而,为什么这行不通呢?
http://docs.mongodb.org/manual/reference/mongoexport/#cmdoption-mongoexport--collection
我的MongoDB版本是2.0.6。
当前回答
如果您正在处理远程数据库,您可以尝试这些命令,前提是您不介意输出是BSON
1. 转储为gzip存档
mongodump --uri="mongodb://YOUR_USER_ID:YOUR_PASSWORD@YOUR_HOST_IP/YOUR_DB_NAME" --gzip --archive > YOUR_FILE_NAME
2. 还原(将数据库从一个数据库复制到另一个数据库)
mongorestore --uri="mongodb://$targetUser:$targetPwd@$targetHost/$targetDb" --nsFrom="$sourceDb.*" --nsTo="$targetDb.*" --gzip --archive
其他回答
如果你有这样的问题: Failed:不能创建会话:不能连接到服务器:connection(): auth error: sasl conversation error: unable to authenticate using mechanism " sran - sha -1": (AuthenticationFailed)认证失败。
然后添加——authenticationDatabase admin
eg:
mongodb -h 192.168.20.30:27018——authenticationDatabase admin -u dbAdmin -p dbPassword -d dbName -o path/to/folder
这是实现目标最简单的方法。
mongodb -d db_name -o path/filename.json
对于本地和远程转储和恢复:
为当地
当地的转储
mongodump -d mydb -o ./mongo-backup
当地的恢复
mongorestore -d mydb ./mongo-backup/mydb
为远程
远程转储
mongodump --uri "mongodb+srv://Admin:MYPASS@appcluster.15lf4.mongodb.net/mytestdb" -o ./mongo-backup
远程恢复
mongorestore --uri "mongodb+srv://Admin:MYPASS@appcluster.15lf4.mongodb.net/mytestdb" ./mongo-backup/mytestdb
更新:
如果你正在使用mongo 4.0,你可能会遇到一个快照错误,那么你可以运行这个参数:——forceTableScan。更多信息请参见这里。错误是这样的:
mongodump error reading collection: BSON field 'FindCommandRequest.snapshot' is an unknown field.
如果你愿意,你可以将所有的集合导出到csv,而不需要指定——fields(将导出所有字段)。
从http://drzon.net/export-mongodb-collections-to-csv-without-specifying-fields/运行这个bash脚本
OIFS=$IFS;
IFS=",";
# fill in your details here
dbname=DBNAME
user=USERNAME
pass=PASSWORD
host=HOSTNAME:PORT
# first get all collections in the database
collections=`mongo "$host/$dbname" -u $user -p $pass --eval "rs.slaveOk();db.getCollectionNames();"`;
collections=`mongo $dbname --eval "rs.slaveOk();db.getCollectionNames();"`;
collectionArray=($collections);
# for each collection
for ((i=0; i<${#collectionArray[@]}; ++i));
do
echo 'exporting collection' ${collectionArray[$i]}
# get comma separated list of keys. do this by peeking into the first document in the collection and get his set of keys
keys=`mongo "$host/$dbname" -u $user -p $pass --eval "rs.slaveOk();var keys = []; for(var key in db.${collectionArray[$i]}.find().sort({_id: -1}).limit(1)[0]) { keys.push(key); }; keys;" --quiet`;
# now use mongoexport with the set of keys to export the collection to csv
mongoexport --host $host -u $user -p $pass -d $dbname -c ${collectionArray[$i]} --fields "$keys" --csv --out $dbname.${collectionArray[$i]}.csv;
done
IFS=$OIFS;
如果您想连接远程mongoDB服务器(如mongolab.com),则应该传递连接凭据 如。
mongoexport -h id.mongolab.com:60599 -u username -p password -d mydb -c mycollection -o mybackup.json