我想通过命令导出MongoDB中的所有集合:

mongoexport -d dbname -o Mongo.json

结果是: 没有指定集合!

手册说,如果你不指定一个集合,所有的集合都将被导出。 然而,为什么这行不通呢?

http://docs.mongodb.org/manual/reference/mongoexport/#cmdoption-mongoexport--collection

我的MongoDB版本是2.0.6。


当前回答

我需要Windows批处理脚本版本。这个帖子很有用,所以我想我也会把我的答案贡献给它。

mongo "{YOUR SERVER}/{YOUR DATABASE}" --eval "rs.slaveOk();db.getCollectionNames()" --quiet>__collections.txt
for /f %%a in ('type __collections.txt') do @set COLLECTIONS=%%a
for %%a in (%COLLECTIONS%) do mongoexport --host {YOUR SERVER} --db {YOUR DATABASE} --collection %%a --out data\%%a.json
del __collections.txt

我在使用set /p COLLECTIONS=<__collections.txt时有一些问题,因此使用了复杂的for /f方法。

其他回答

如果你愿意,你可以将所有的集合导出到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;

导出所有集合:

mongodump -d database_name -o directory_to_store_dumps

要恢复它们:

mongorestore -d database_name directory_backup_where_mongodb_tobe_restored

这是实现目标最简单的方法。

mongodb -d db_name -o path/filename.json

这是我用来实现该结果的bash脚本。该脚本被概括为4个输入(主机url、数据库、用户名和密码),因此可以在任何mongo数据库上使用。

dburl=$1
username=$3
password=$4
db=$2

mongoAccess=mongodb+srv://$username:$password@$dburl/$db

Collections=$(mongo $mongoAccess --quiet --eval "db.getCollectionNames()" | sed 's/,/ /g' | tail +6)

#echo $Collections

for col in $Collections
do
    if [ "$col" = "[" ] || [ "$col" = "]" ]
    then
        continue
    else
        echo "Exporting $col"
        mongoexport --uri $mongoAccess --collection=$col --type json --out output-$col.json
    fi
    
done

之前的答案解释得很好,我添加了我的答案,以帮助您处理远程密码保护数据库

mongodump --host xx.xxx.xx.xx --port 27017 --db your_db_name --username your_user_name --password your_password --out /target/folder/path