1. 在mongodb安裝目錄的bin目錄下有一個資料匯出工具:mongoexport.exe,我們可以開啟一個命令視窗,切換到該目錄下並執行mongoexport,就可以看到使用該工具的很多參數說明。
假設mongodb的安裝目錄為D:\program\mongodb,那麼可以通過以下方式瞭解匯出工具的使用:
>d:
>D:\program\mongodb\bin
>mongoexport
--help produce help message
-v [ --verbose ] be more verbose (include multiple time
verbosity e.g. -vvvvv)
--version print the program's version and exit
........
2. 常用資料匯出方式
首先,在MongoDB中新增一個localdb,以及建立集合user並插入一些對象。
>use localdb
>db.user.insert({"name" : "ming", "age" : 2 })
>db.user.insert({"name" : "lisi", "age" : 20 })
那麼,接下來就可以使用以下方式匯出user表中的資料。其中,-d代表指明從哪個資料庫中匯出資料;-c代表從哪個集合中匯出資料;-o指明匯出的資料輸出到哪個檔案中。
>mongoexport -d localdb -c user -o user.dat
匯出成功後,開啟user.dat檔案,匯出的資料如下所示:
{ "_id" : { "$oid" : "4eed9f9ca939118694cf05e4" }, "name" : "ming", "age" : 2 }
{ "_id" : { "$oid" : "4ef1f3cf3bd18218e6bdfa31" }, "name" : "lisi", "age" : "20" }
3. 匯出為CVS檔案
如果要匯出集合中指定欄位的資料存到CVS檔案中,可以使用如下命令:
>mongoexport -d localdb -c user -f _id,name --csv -o user.csv
匯出的user.cvs檔案的內容如下:
{ "_id" : { "$oid" : "4eed9f9ca939118694cf05e4" }, "name" : "ming" }
{ "_id" : { "$oid" : "4ef1f3cf3bd18218e6bdfa31" }, "name" : "lisi" }
4. mongoexport參數列表
options:
--help produce help message
-v [ --verbose ] be more verbose (include multiple times for more verbosity e.g. -vvvvv)
--version print the program's version and exit
-h [ --host ] arg mongo host to connect to ( <set name>/s1,s2 for sets)
--port arg server port. Can also use --host hostname:port
--ipv6 enable IPv6 support (disabled by default)
-u [ --username ] arg username
-p [ --password ] arg password
--dbpath arg directly access mongod database files in the given
path, instead of connecting to a mongod server -
needs to lock the data directory, so cannot be used
if a mongod is currently accessing the same path
--directoryperdb if dbpath specified, each db is in a separate directory
--journal enable journaling
-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
--fieldFile arg file with fields names - 1 per line
-q [ --query ] arg query filter, as a JSON string
--csv export to csv instead of json
-o [ --out ] arg output file; if not specified, stdout is used
--jsonArray output to a json array rather than one object per line
-k [ --slaveOk ] arg (=1) use secondaries for export if available, default true