简体   繁体   中英

How to export all collections in MongoDB

有人可以告诉我如何通过命令行一次导出所有集合(成JSON格式)

Generally you want to use mongoexport or mongodump but each of those only works on a single collection.

To get all collections and export them all you need to run some type of script that can locate and then loop through everything. On linux it would be something like this:

#!/bin/bash

DB=$1
Collections=$(mongo localhost:27017/$DB --quiet --eval "db.getCollectionNames()" | sed 's/,/ /g')

for collection in $Collections; do
   mongoexport -d <DATABASE_NAME> -c $collection -o $collection.json
done

You'll need to this into a script file and then run it. I haven't tested the above myself but it is hopefully error free.

Steve's script generates the files with quotes at the ends. For this to not happen, the pattern is improved.

Improving the above script

#!/bin/bash

DB=$1
Collections=$(mongo localhost:27017/$DB --quiet --eval "db.getCollectionNames()" | sed 's/[^"[:alnum:]]/ /g')

for collection in $Collections; do
   mongoexport -d $DB -c $collection -o ./$collection.json
done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM