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

mongoexport -d dbname -o Mongo.json

结果是: 没有指定集合!

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

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

我的MongoDB版本是2.0.6。


当前回答

对于懒人,使用mongodb,它更快:

mongodump -d <database_name> -o <directory_backup>

然后“恢复/导入”它(从directory_backup/dump/):

mongorestore -d <database_name> <directory_backup>

这样,您就不需要单独处理所有集合。只需指定数据库。

注意,我不建议使用mongodb /mongorestore存储大数据。它非常慢,一旦超过10/20GB的数据,可能需要几个小时才能恢复。

其他回答

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

mongodb -d db_name -o path/filename.json

以下是恢复导出数据库时对我有效的方法:

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;

这是我用来实现该结果的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