mongodb的bin目錄下提供了一個mongoexport.exe的程序,可以用於導出數據。
使用$ mongoexport --help 可以查看相關參數的說明:
$ mongoexport --help
Export MongoDB data to CSV, TSV or JSON files.
Options:
--help produce help message
--quiet silence all non error diagnostic messages
-h [ --host ] arg mongo host to connect to ( <set name>/s1,s2 for sets) 主機名 默認127.0.0.1
--port arg server port. Can also use --host hostname:port 端口 默認27017
-u [ --username ] arg username 用戶名
-p [ --password ] arg password 密碼
-d [ --db ] arg database to use 數據庫名
-c [ --collection ] arg collection to use (some commands) 集合名
-f [ --fields ] arg comma separated list of field names e.g. -f name,age 字段名,導出到csv時候需要
--fieldFile arg file with field names - 1 per line
--csv export to csv instead of json 導出csv格式
-o [ --out ] arg output file; if not specified, stdout is used 導出文件名
-q [ --query ] arg query filter, as a JSON string, e.g., '{x:{$gt:1}}' 查詢條件,使用json格式
--skip arg (=0) documents to skip, default 0 跳過數據,偏移,默認爲0
--limit arg (=0) limit the numbers of documents returned, default all 限制返回的documents數量,默認爲0
--sort arg sort order, as a JSON string, e.g., '{x:1}' 排序
eg:
導出到json:
$ mongoexport.exe -d TestDB -c TestCollection -o ./test.json
導出到csv:
$ mongoexport.exe --csv -f _id,f1,f2,f3,f4,f5,f6,f7 -d TestDB -c TestCollection -o ./test.csv
如果含有中文字符,打開csv文件可能會有亂碼,用記事本另存成utf-8格式就好了。
在使用-q 查詢條件過濾數據的時候,注意兩邊的 ’ (單引號)
當數據量很大時候,可以使用--skip 配合 --limit,限制單個文件的數據量,方便普通用戶查看
另外,可以使用mongodump命令備份數據:
$ mongodump -h 127.0.0.1:27017 -d testDB -o ./data