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

mongoexport -d dbname -o Mongo.json

结果是: 没有指定集合!

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

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

我的MongoDB版本是2.0.6。


当前回答

我把所有的收集倾倒在robo3t上。 我在vagrant/homestead上运行下面的命令。这是我的工作

mongodump --host localhost --port 27017 --db db_name --out db_path

其他回答

如果你愿意,你可以将所有的集合导出到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脚本。只需使用2个参数(数据库名称,存储文件的dir)运行它。

#!/bin/bash

if [ ! $1 ]; then
        echo " Example of use: $0 database_name [dir_to_store]"
        exit 1
fi
db=$1
out_dir=$2
if [ ! $out_dir ]; then
        out_dir="./"
else
        mkdir -p $out_dir
fi

tmp_file="fadlfhsdofheinwvw.js"
echo "print('_ ' + db.getCollectionNames())" > $tmp_file
cols=`mongo $db $tmp_file | grep '_' | awk '{print $2}' | tr ',' ' '`
for c in $cols
do
    mongoexport -d $db -c $c -o "$out_dir/exp_${db}_${c}.json"
done
rm $tmp_file

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

mongodb -d db_name -o path/filename.json

如果你可以接受bson格式,那么你可以使用带有相同-d标志的mongodb实用程序。它将以bson格式将所有集合转储到转储目录(默认的,可以通过-o选项更改)。然后可以使用mongorestore实用程序导入这些文件。

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