mongoexport 是 MongoDB 提供的一个命令行工具,用于将集合中的数据导出为 JSON 或 CSV 格式。
mongoexport --uri="<connection_string>" \
--collection=<collection_name> \
--db=<database_name> \
--out=<output_file>--uri:指定 MongoDB 的连接字符串(包含主机、端口、认证信息等)。--collection:指定要导出的集合名称。--db:指定数据库名称。--out:指定导出文件的路径和名称(可选,默认输出到标准输出)。mongoexport --uri="mongodb://username:password@localhost:27017" \
--db=myDatabase \
--collection=myCollection \
--out=/path/to/output.json说明:
/path/to/output.json 文件中。--out 参数,数据将直接打印到终端。如果只想导出满足特定条件的数据,可以使用 --query 参数。
mongoexport --uri="mongodb://username:password@localhost:27017" \
--db=myDatabase \
--collection=myCollection \
--query='{"status": "active"}' \
--out=/path/to/active_records.json说明:
--query 参数接受一个 JSON 字符串,作为查询条件。status 字段等于 "active" 的文档。如果只想导出某些字段,可以使用 --fields 参数。
mongoexport --uri="mongodb://username:password@localhost:27017" \
--db=myDatabase \
--collection=myCollection \
--fields="_id,name,age" \
--out=/path/to/selected_fields.json说明:
--fields 参数接受一个逗号分隔的字段列表。_id、name 和 age 字段。如果需要将数据导出为 CSV 格式,可以使用 --type=csv 参数,并配合 --fields 指定字段。
mongoexport --uri="mongodb://username:password@localhost:27017" \
--db=myDatabase \
--collection=myCollection \
--type=csv \
--fields="_id,name,age" \
--out=/path/to/output.csv说明:
--type=csv 指定导出格式为 CSV。--fields 参数是必须的,因为 CSV 格式需要明确字段顺序。参数 | 描述 |
|---|---|
| 限制导出的文档数量。 |
| 跳过指定数量的文档后再开始导出。 |
| 指定排序规则(JSON 格式)。 |
| 强制全表扫描(在有索引的情况下仍扫描所有文档)。 |
| 指定认证数据库(例如 |
| 启用 SSL 连接(如果 MongoDB 启用了 SSL)。 |
mongoexport --uri="mongodb://username:password@localhost:27017" \
--db=myDatabase \
--collection=myCollection \
--query='{"status": "active"}' \
--fields="_id,name,age" \
--type=json \
--sort='{"age": -1}' \
--limit=100 \
--out=/path/to/filtered_sorted_limited.json说明:
status 为 "active" 的文档。_id、name 和 age 字段。age 字段降序排序。mongoexport 的用户对目标数据库和集合具有读取权限。--limit 或分批次导出的方式来处理。--out 参数,数据将直接打印到终端。可以通过管道操作将其重定向到其他工具或文件中:mongoexport --uri="mongodb://localhost:27017" \
--db=myDatabase \
--collection=myCollection > output.json--fields 参数指定字段列表,否则会报错。mongoexport 工具版本与 MongoDB 服务器版本兼容。mongoexport 可以方便地将 MongoDB 集合中的数据导出为 JSON 或 CSV 格式。--query、--fields、--sort 等参数,可以灵活控制导出内容。--limit 或分批次导出,避免资源耗尽。原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。