MongoDB 数据导出mongoexport(可导出为txt或csv)

1、概述 mongoexport命令行用.

1、概述

mongoexport命令行用于数据的导出,默认导出的文件格式为JSON格式。当然也可以指定特定的文件格式。

2、语法

  1. C:\mongo\bin>mongoexport -help
  2. options:
  3.   –help                  produce help message
  4.   -v [ –verbose ]        be more verbose (include multiple times for more
  5.                           verbosity e.g. -vvvvv)
  6.   -h [ –host ] arg       mongo host to connect to ( <set name>/s1,s2 for sets)
  7.   –port arg              server port. Can also use –host hostname:port
  8.   –ipv6                  enable IPv6 support (disabled by default)
  9.   -u [ –username ] arg   username
  10.   -p [ –password ] arg   password
  11.   –dbpath arg            directly access mongod database files in the given
  12.                           path, instead of connecting to a mongod  server –
  13.                           needs to lock the data directory, so cannot be used
  14.                           if a mongod is currently accessing the same path
  15.   –directoryperdb        if dbpath specified, each db is in a separate
  16.                           directory
  17.   -d [ –db ] arg         database to use
  18.   -c [ –collection ] arg collection to use (some commands)
  19.   -f [ –fields ] arg     comma separated list of field names e.g. -f name,age
  20.   –fieldFile arg         file with fields names – 1 per line
  21.   -q [ –query ] arg      query filter, as a JSON string
  22.   –csv                   export to csv instead of json
  23.   -o [ –out ] arg        output file; if not specified, stdout is used
  24.   –jsonArray             output to a json array rather than one object per
  25.                           Line

说明:

-h:数据库宿主机的IP

-u:数据库用户名

-p:数据库密码

-d:数据库名字

-c:集合的名字

-f:导出的列名

-q:导出数据的过滤条件

–csv:导出格式为csv

3、示例

现有如下数据:

现在进行全部导出操作,默认导出的是JSON格式的数据:

上述命令行:从test数据库中导出集合为emp的数据,保存文件到emp.dat中。

查看:

下面是导出csv格式的命令:

查看:

实战示例:

1、将集合中account和balance字段导出为txt格式

mongoexport -h 127.0.0.1 –port 27017 –username username  –password password  –collection accounts -f account,balance –out /usr/local/bak/db/1.txt –db dbname

2、将集合中account和balance字段导出为csv格式

mongoexport -h 127.0.0.1 –port 27017 –username username –csv –password password  –collection accounts -f account,balance –out /usr/local/bak/db/1.csv –db dbname