使用 mongoexport 按照条件导出 csv 文件

输入 mongoexport --help 查看相关的参数:

Usage:
  mongoexport <options>

Export data from MongoDB in CSV or JSON format.

See http://docs.mongodb.org/manual/reference/program/mongoexport/ for more information.

general options:
      --help                                      print usage
      --version                                   print the tool version and exit

verbosity options:
  -v, --verbose=<level>                           more detailed log output (include multiple times for more verbosity, e.g. -vvvvv, or specify a numeric value, e.g. --verbose=N)
      --quiet                                     hide all log output

connection options:
  -h, --host=<hostname>                           mongodb host to connect to (setname/host1,host2 for replica sets)
      --port=<port>                               server port (can also use --host hostname:port)

authentication options:
  -u, --username=<username>                       username for authentication
  -p, --password=<password>                       password for authentication
      --authenticationDatabase=<database-name>    database that holds the user's credentials
      --authenticationMechanism=<mechanism>       authentication mechanism to use

namespace options:
  -d, --db=<database-name>                        database to use
  -c, --collection=<collection-name>              collection to use

output options:
  -f, --fields=<field>[,<field>]*                 comma separated list of field names (required for exporting CSV) e.g. -f "name,age"
      --fieldFile=<filename>                      file with field names - 1 per line
      --type=<type>                               the output format, either json or csv (defaults to 'json') (default: json)
  -o, --out=<filename>                            output file; if not specified, stdout is used
      --jsonArray                                 output to a JSON array rather than one object per line
      --pretty                                    output JSON formatted to be human-readable
      --noHeaderLine                              export CSV data without a list of field names at the first line

querying options:
  -q, --query=<json>                              query filter, as a JSON string, e.g., '{x:{$gt:1}}'
      --queryFile=<filename>                      path to a file containing a query filter (JSON)
  -k, --slaveOk                                   allow secondary reads if available (default true) (default: false)
      --readPreference=<string>|<json>            specify either a preference name or a preference json object
      --forceTableScan                            force a table scan (do not use $snapshot)
      --skip=<count>                              number of documents to skip
      --limit=<count>                             limit the number of documents to export
      --sort=<json>                               sort order, as a JSON string, e.g. '{x:1}'
      --assertExists                              if specified, export fails if the collection does not exist (default: false)

在帮助里面展示了各个参数的使用说明。我们进入参考页面看一下:
http://docs.mongodb.org/manual/reference/program/mongoexport/

执行程序示例

创建一个数据库表并且插入测试数据:

use test
db.traffic.insert( { _id: 1, volume: NumberLong('2980000'), date: new Date() } )

使用 mongoimport 导出这条数据: (退出 mongo 交互环境,在终端执行)

mongoexport --db test --collection traffic --out traffic.json

查看一眼导出的文件:

cat traffic.json
{"_id":1.0,"volume":{"$numberLong":"2980000"},"date":{"$date":"2019-07-19T03:25:20.163Z"}}

参数说明

获取帮助

– help 如上所述,mongoimport --help 就可以获取命令的使用帮助。

获取导出日志详情

–verbose, -v
增加标准输出或日志文件中返回的内部报告数量。-v通过多次包含选项来增加表单的详细程度,(例如-vvvvv)

mongoexport --db test --collection traffic -vvvv --out traffic.json
2019-07-19T11:37:38.713+0800	will listen for SIGTERM, SIGINT, and SIGKILL
2019-07-19T11:37:38.730+0800	connected to: localhost
2019-07-19T11:37:38.730+0800	exported 2 records
安静模式

–quiet
以安静模式运行mongoexport,尝试限制输出量。

查看版本
mongoimport --version 
mongoimport version: r3.4.2
git version: 3f76e40c105fc223b3e5aac3e20dcd026b83b38b
Go version: go1.7
   os: darwin
   arch: amd64
   compiler: gc

中间还有很多参数,暂时略过,有时间再写。 然后看到了这次的正题,在导出语句中进行查询: --query

按照条件导出

–query , -q
举例: 我们先去插入这些数据:

{ "_id" : ObjectId("51f0188846a64a1ed98fde7c"), "a" : 1, "date" : ISODate("1960-05-01T00:00:00Z") }
{ "_id" : ObjectId("520e61b0c6646578e3661b59"), "a" : 1, "b" : 2, "date" : ISODate("1970-05-01T00:00:00Z") }
{ "_id" : ObjectId("520e642bb7fa4ea22d6b1871"), "a" : 2, "b" : 3, "c" : 5, "date" : ISODate("2010-05-01T00:00:00Z") }
{ "_id" : ObjectId("520e6431b7fa4ea22d6b1872"), "a" : 3, "b" : 3, "c" : 6, "date" : ISODate("2015-05-02T00:00:00Z") }
{ "_id" : ObjectId("520e6445b7fa4ea22d6b1873"), "a" : 5, "b" : 6, "c" : 8, "date" : ISODate("2018-03-01T00:00:00Z") }
{ "_id" : ObjectId("5cd0de910dbce4346295ae28"), "a" : 15, "b" : 5, "date" : ISODate("2015-03-01T00:00:00Z") }

查看一下我们插入的结果:

> db.records.find()
{ "_id" : ObjectId("51f0188846a64a1ed98fde7c"), "a" : 1, "date" : ISODate("1960-05-01T00:00:00Z") }
{ "_id" : ObjectId("520e61b0c6646578e3661b59"), "a" : 1, "b" : 2, "date" : ISODate("1970-05-01T00:00:00Z") }
{ "_id" : ObjectId("520e642bb7fa4ea22d6b1871"), "a" : 2, "b" : 3, "c" : 5, "date" : ISODate("2010-05-01T00:00:00Z") }
{ "_id" : ObjectId("520e6431b7fa4ea22d6b1872"), "a" : 3, "b" : 3, "c" : 6, "date" : ISODate("2015-05-02T00:00:00Z") }
{ "_id" : ObjectId("520e6445b7fa4ea22d6b1873"), "a" : 5, "b" : 6, "c" : 8, "date" : ISODate("2018-03-01T00:00:00Z") }
{ "_id" : ObjectId("5cd0de910dbce4346295ae28"), "a" : 15, "b" : 5, "date" : ISODate("2015-03-01T00:00:00Z") }

然后我们需要按照一定的条件导出: 即 a 的值大于等于 3 以及时间小于 2106年 1 月 1 日的
符合条件的只有两条数据

mongoexport -d test -c records -q '{ a: { $gte: 3 }, date: { $lt: { "$date": "2016-01-01T00:00:00.000Z" } } }' --out exportdir/myRecords.json

查看执行结果文件:

cat myRecords.json
{"_id":{"$oid":"520e6431b7fa4ea22d6b1872"},"a":3.0,"b":3.0,"c":6.0,"date":{"$date":"2015-05-02T00:00:00.000Z"}}
{"_id":{"$oid":"5cd0de910dbce4346295ae28"},"a":15.0,"b":5.0,"date":{"$date":"2015-03-01T00:00:00.000Z"}}

尝试导出csv文件试试:

mongoexport -d test -c records -q '{ a: { $gte: 3 }, date: { $lt: { "$date": "2016-01-01T00:00:00.000Z" } } }' --out exportdir/myRecords.csv

发现这样子写只是后缀改变了而已,还是保存的是 json 的格式。
在命令行显式指定一下使用 csv 格式的导出文件:

mongoexport -d test -c records -q '{ a: { $gte: 3 }, date: { $lt: { "$date": "2016-01-01T00:00:00.000Z" } } }' --type=csv --out exportdir/myRecords.csv

给了一个执行失败的错误提示:

Failed: CSV mode requires a field list

意思是如果使用 csv 文件的方式,我们需要指定被导出的字段:

mongoexport -d test -c records -q '{ a: { $gte: 3 }, date: { $lt: { "$date": "2016-01-01T00:00:00.000Z" } } }' --fields "_id,a,b,c,date"  --type=csv --out exportdir/myRecords.csv

如果被指定的字段过多,我们也可以将字段名写入文件,注意一个字段写一行:

fields.txt

_id
a
b
c
date

在命令行使用 --fieldFile 来指定使用的文件:

mongoexport -d test -c records -q '{ a: { $gte: 3 }, date: { $lt: { "$date": "2016-01-01T00:00:00.000Z" } } }' --fieldFile  fields.txt  --type=csv --out exportdir/myRecords.csv

实例

在这里插入图片描述

### 将 MongoDB 数据导出CSV 文件 为了将 MongoDB 中的数据导出CSV 文件,可以采用多种方法。以下是几种常见的解决方案: #### 方法一:使用 `mongoexport` 命令行工具 命令行工具 `mongoexport` 是一种简单而有效的方式,适用于大多数场景下的数据导出需求。 ```bash mongoexport --collection score \ --type=csv --fields=name,age,province,Chinese,English,Math,Chemistry \ --out D:\tmp\exp_data.csv ``` 此命令会连接到本地运行的 MongoDB 实例中的 `student` 数据库,并从中提取名为 `score` 的集合里的文档,随后按照指定字段列表将其保存成 CSV 文件[^3]。 #### 方法二:通过 Java 程序实现自定义逻辑 对于更复杂的需求或是希望集成到应用程序内的场合,则可以通过编写 Java 应用来完成这项工作。下面是一个简单的例子来展示如何操作: ```java import com.mongodb.client.MongoClients; import org.bson.Document; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class ExportToCsv { public static void main(String[] args) throws IOException { try (var client = MongoClients.create("mongodb://localhost:27017")) { var collection = client.getDatabase("student").getCollection("score"); List<String> lines = new ArrayList<>(); for (Document doc : collection.find()) { String line = String.format("%s,%d,%s", doc.getString("name"), doc.getInteger("age"), doc.getString("province")); // 添加更多字段... lines.add(line); } try (FileWriter writer = new FileWriter("D:/tmp/exp_data_java.csv")) { writer.write(String.join("\n", lines)); } } } } ``` 这段代码展示了怎样利用官方提供的 Java 驱动程序读取 MongoDB 文档并写入 CSV 文件中。注意这里仅作为概念验证用途,在实际项目里可能还需要考虑异常处理、性能优化等问题[^1]。 #### 方法三:借助第三方 ETL 工具或框架 除了上述两种方式外,还可以选择一些专门用于ETL(Extract Transform Load)过程的专业软件包来进行批量迁移作业。这些工具有助于简化流程管理以及提高效率。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值