我想通过命令导出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。
当前回答
导出所有集合:
mongodump -d database_name -o directory_to_store_dumps
要恢复它们:
mongorestore -d database_name directory_backup_where_mongodb_tobe_restored
其他回答
如果您正在处理远程数据库,您可以尝试这些命令,前提是您不介意输出是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
以下是恢复导出数据库时对我有效的方法:
Mongorestore -d 0 ./0——drop
其中。/包含导出的bson文件。注意——drop将覆盖现有数据。
如果你愿意,你可以将所有的集合导出到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;
通过这个命令导出整个Mongo DB
mongoexport –db database_name –collection collection_name –out path_or_filename.json
即使在mongo版本4中,也没有办法一次导出所有的集合。将指定的集合从运行在端口27017上的本地MongoDB实例导出到指定的输出文件,您可以使用以下命令:
.\mongoexport.exe——db=xstaging——collection=products——out=c:/xstaging.products.json