如何在 MongoDB 中将集合导出为 CSV?

发布于 2024-11-26 06:51:48 字数 208 浏览 4 评论 0原文

如何将 MongoDB 集合中的所有记录导出到 .csv 文件?

mongoexport --host localhost --db dbname --collection name --type=csv > test.csv

这要求我指定需要导出的字段的名称。我可以只导出所有字段而不指定字段名称吗?

How do you export all the records in a MongoDB collection to a .csv file?

mongoexport --host localhost --db dbname --collection name --type=csv > test.csv

This asks me to specify name of the fields I need to export. Can I just export all the fields without specifying the names of fields?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

痕至 2024-12-03 06:51:48

@karoly-horvath 说得对。 csv 需要字段。

根据 MongoDB 问题跟踪器 https://jira.mongodb.org/browse/SERVER- 中的此错误4224 导出到 csv 时必须提供字段。文档对此并不清楚。这就是错误的原因。

试试这个:

mongoexport --host localhost --db dbname --collection name --csv --out text.csv --fields firstName,middleName,lastName

更新:

此提交:https://github.com/mongodb/mongo-tools/commit/586c00ef09c32c77907bd20d722049ed23065398 修复了 3.0.0-rc10 及更高版本的文档。它更改

Fields string `long:"fields" short:"f" description:"comma separated list of field names, e.g. -f name,age"`

Fields string `long:"fields" short:"f" description:"comma separated list of field names (required for exporting CSV) e.g. -f \"name,age\" "`

版本3.0及以上:

您应该使用--type=csv而不是--csv,因为它已被弃用。

更多详细信息: https://docs.mongodb.com /manual/reference/program/mongoexport/#export-in-csv-format

完整命令:

mongoexport --host localhost --db dbname --collection name --type=csv --out text.csv --fields firstName,middleName,lastName

@karoly-horvath has it right. Fields are required for csv.

According to this bug in the MongoDB issue tracker https://jira.mongodb.org/browse/SERVER-4224 you MUST provide the fields when exporting to a csv. The docs are not clear on it. That is the reason for the error.

Try this:

mongoexport --host localhost --db dbname --collection name --csv --out text.csv --fields firstName,middleName,lastName

UPDATE:

This commit: https://github.com/mongodb/mongo-tools/commit/586c00ef09c32c77907bd20d722049ed23065398 fixes the docs for 3.0.0-rc10 and later. It changes

Fields string `long:"fields" short:"f" description:"comma separated list of field names, e.g. -f name,age"`

to

Fields string `long:"fields" short:"f" description:"comma separated list of field names (required for exporting CSV) e.g. -f \"name,age\" "`

VERSION 3.0 AND ABOVE:

You should use --type=csv instead of --csv since it has been deprecated.

More details: https://docs.mongodb.com/manual/reference/program/mongoexport/#export-in-csv-format

Full command:

mongoexport --host localhost --db dbname --collection name --type=csv --out text.csv --fields firstName,middleName,lastName
任谁 2024-12-03 06:51:48

此外,逗号分隔的字段名称之间不允许有空格。

坏的:
-f 名字,姓氏

好:
-f 名字,姓氏

Also, you are not allowed spaces between comma separated field names.

BAD:
-f firstname, lastname

GOOD:
-f firstname,lastname

笑脸一如从前 2024-12-03 06:51:48
mongoexport  --help
....
-f [ --fields ] arg     comma separated list of field names e.g. -f name,age
--fieldFile arg         file with fields names - 1 per line

您必须手动指定它,如果您考虑一下,它就很有意义。 MongoDB 是无模式的;另一方面,CSV 有固定的列布局。如果不知道不同文档中使用了哪些字段,就不可能输出 CSV 转储。

如果您有固定的模式,也许您可​​以检索一个文档,使用脚本从中获取字段名称并将其传递给 mongoexport。

mongoexport  --help
....
-f [ --fields ] arg     comma separated list of field names e.g. -f name,age
--fieldFile arg         file with fields names - 1 per line

You have to manually specify it and if you think about it, it makes perfect sense. MongoDB is schemaless; CSV, on the other hand, has a fixed layout for columns. Without knowing what fields are used in different documents it's impossible to output the CSV dump.

If you have a fixed schema perhaps you could retrieve one document, harvest the field names from it with a script and pass it to mongoexport.

笨笨の傻瓜 2024-12-03 06:51:48

如果需要,您可以将所有集合导出到 csv,而无需指定 --fields (将导出所有字段)。

来自 http://drzon.net/export-mongodb-collections -to-csv-without-specifying-fields/ 运行此 bash 脚本

OIFS=$IFS;
IFS=",";

# fill in your details here
dbname=DBNAME
user=USERNAME
pass=PASSWORD
host=HOSTNAME:PORT

# first get all collections in the database
collections=`mongo "$host/$dbname" -u $user -p $pass --eval "rs.slaveOk();db.getCollectionNames();"`;
collections=`mongo $dbname --eval "rs.slaveOk();db.getCollectionNames();"`;
collectionArray=($collections);

# for each collection
for ((i=0; i<${#collectionArray[@]}; ++i));
do
    echo 'exporting collection' ${collectionArray[$i]}
    # get comma separated list of keys. do this by peeking into the first document in the collection and get his set of keys
    keys=`mongo "$host/$dbname" -u $user -p $pass --eval "rs.slaveOk();var keys = []; for(var key in db.${collectionArray[$i]}.find().sort({_id: -1}).limit(1)[0]) { keys.push(key); }; keys;" --quiet`;
    # now use mongoexport with the set of keys to export the collection to csv
    mongoexport --host $host -u $user -p $pass -d $dbname -c ${collectionArray[$i]} --fields "$keys" --csv --out $dbname.${collectionArray[$i]}.csv;
done

IFS=$OIFS;

If you want, you can export all collections to csv without specifying --fields (will export all fields).

From http://drzon.net/export-mongodb-collections-to-csv-without-specifying-fields/ run this bash script

OIFS=$IFS;
IFS=",";

# fill in your details here
dbname=DBNAME
user=USERNAME
pass=PASSWORD
host=HOSTNAME:PORT

# first get all collections in the database
collections=`mongo "$host/$dbname" -u $user -p $pass --eval "rs.slaveOk();db.getCollectionNames();"`;
collections=`mongo $dbname --eval "rs.slaveOk();db.getCollectionNames();"`;
collectionArray=($collections);

# for each collection
for ((i=0; i<${#collectionArray[@]}; ++i));
do
    echo 'exporting collection' ${collectionArray[$i]}
    # get comma separated list of keys. do this by peeking into the first document in the collection and get his set of keys
    keys=`mongo "$host/$dbname" -u $user -p $pass --eval "rs.slaveOk();var keys = []; for(var key in db.${collectionArray[$i]}.find().sort({_id: -1}).limit(1)[0]) { keys.push(key); }; keys;" --quiet`;
    # now use mongoexport with the set of keys to export the collection to csv
    mongoexport --host $host -u $user -p $pass -d $dbname -c ${collectionArray[$i]} --fields "$keys" --csv --out $dbname.${collectionArray[$i]}.csv;
done

IFS=$OIFS;
夜吻♂芭芘 2024-12-03 06:51:48

适用于我使用 mongo 远程连接到 docker 容器:4.2.6

mongoexport -h mongodb:27017 --authenticationDatabase=admin -u username -p password -d database -c collection -q {"created_date": { "$gte": { "$date": "2020-08-03T00:00:00.000Z" }, "$lt": { "$date": "2020-08-09T23:59:59.999Z" } } } --fields=somefield1,somefield2 --type=csv --out=/archive.csv

works for me remoting to a docker container with mongo:4.2.6

mongoexport -h mongodb:27017 --authenticationDatabase=admin -u username -p password -d database -c collection -q {"created_date": { "$gte": { "$date": "2020-08-03T00:00:00.000Z" }, "$lt": { "$date": "2020-08-09T23:59:59.999Z" } } } --fields=somefield1,somefield2 --type=csv --out=/archive.csv
内心旳酸楚 2024-12-03 06:51:48

使用 Mongo Compass 工具轻松导出 csv 或 json 文件

Mongo Compass 作为 MongoDB 的 GUI,MongoDB Compass 允许您对文档结构、查询、索引、文档验证等做出更明智的决策。商业订阅包括 MongoDB Compass 的技术支持。
https://www.mongodb.com/try/download/compass
输入图像描述这里

Easy export csv or json file With Mongo Compass tool

Mongo Compass As the GUI for MongoDB, MongoDB Compass allows you to make smarter decisions about document structure, querying, indexing, document validation, and more. Commercial subscriptions include technical support for MongoDB Compass.
https://www.mongodb.com/try/download/compass
enter image description here

反目相谮 2024-12-03 06:51:48

我无法让 mongoexport 为我做这件事。我发现,要获得所有字段的详尽列表,您需要循环遍历整个集合一次。使用它来生成标头。然后再次循环遍历集合以填充每个文档的这些标题。

我写了一个脚本来做到这一点。将 MongoDB 文档转换为 csv,无论各个文档之间的架构差异如何。

https://github.com/surya-shodan/mongoexportcsv

I could not get mongoexport to do this for me. I found that,to get an exhaustive list of all the fields, you need to loop through the entire collection once. Use this to generate the headers. Then loop through the collection again to populate these headers for each document.

I've written a script to do just this. Converting MongoDB docs to csv irrespective of schema differences between individual documents.

https://github.com/surya-shodan/mongoexportcsv

囍孤女 2024-12-03 06:51:48

另外,如果您想导出内部 json 字段,请使用点(. 运算符)。

JSON记录:

{
    "_id" : "00118685076F2C77",
    "value" : {
        "userIds" : [ 
            "u1"
        ],
        "deviceId" : "dev"
}

带有点运算符的mongoexport命令(使用mongo版本3.4.7):

./mongoexport --host localhost --db myDB --collection myColl
--type=csv --out out.csv --fields value.deviceId,value.userIds

输出 csv:

value.deviceId,value.userIds
d1,"[""u1""]"
d2,"[""u2""]"

注意:确保您不导出数组。它会破坏 CSV 格式,如上面显示的字段 userIds

Also if you want to export inner json fields use dot (. operator).

JSON record:

{
    "_id" : "00118685076F2C77",
    "value" : {
        "userIds" : [ 
            "u1"
        ],
        "deviceId" : "dev"
}

mongoexport command with dot operator (using mongo version 3.4.7):

./mongoexport --host localhost --db myDB --collection myColl
--type=csv --out out.csv --fields value.deviceId,value.userIds

Output csv:

value.deviceId,value.userIds
d1,"[""u1""]"
d2,"[""u2""]"

Note: Make sure you do not export an array. It would corrupt the CSV format like field userIds shown above

暮年 2024-12-03 06:51:48

MongoDB Atlas 用户的解决方案!

添加 --fields 参数作为用双引号括起来的逗号分隔字段名称:

--fields "<FIELD 1>,<FIELD 2>..."

这是完整的示例:

mongoexport --host Cluster0-shard-0/shard1URL.mongodb.net:27017,shard2URL.mongodb.net:27017,shard3URL.mongodb.net:27017 --ssl --username <USERNAME> --password <PASSWORD> --authenticationDatabase admin --db <DB NAME> --collection <COLLECTION NAME> --type <OUTPUT FILE TYPE> --out <OUTPUT FILE NAME> --fields "<FIELD 1>,<FIELD 2>..."

Solution for MongoDB Atlas users!

Add the --fields parameter as comma separated field names enclosed in double inverted quotes:

--fields "<FIELD 1>,<FIELD 2>..."

This is complete example:

mongoexport --host Cluster0-shard-0/shard1URL.mongodb.net:27017,shard2URL.mongodb.net:27017,shard3URL.mongodb.net:27017 --ssl --username <USERNAME> --password <PASSWORD> --authenticationDatabase admin --db <DB NAME> --collection <COLLECTION NAME> --type <OUTPUT FILE TYPE> --out <OUTPUT FILE NAME> --fields "<FIELD 1>,<FIELD 2>..."
往昔成烟 2024-12-03 06:51:48

这对我有用尝试一下

mongoexport --host cluster0-shard-dummy-link.mongodb.net:27017 --db yourdbname --forceTableScan   --collection users --type json --out /var/www/html/user.json --authenticationDatabase admin --ssl --username Yourusername --password Yourpassword

上面的cmd返回用户集合的全部数据
如果您想要过滤字段,请添加 --fields=email,name

This working for me Try it

mongoexport --host cluster0-shard-dummy-link.mongodb.net:27017 --db yourdbname --forceTableScan   --collection users --type json --out /var/www/html/user.json --authenticationDatabase admin --ssl --username Yourusername --password Yourpassword

Above cmd return whole data of the users collection
if you want filter field then add --fields=email,name

全部不再 2024-12-03 06:51:48

对于所有陷入错误的人。

让我给你们一个解决方案,并对其进行简要说明:-

连接命令:-

mongoexport --host your_host --port your_port -u your_username -p your_password --db your_db --collection your_collection --type=csv --out file_name.csv --fields all_the_fields --authenticationDatabase admin

--host --> Mongo 服务器的主机

--port --> Mongo服务器的端口

-u -->用户名

-p -->密码

--db-->您要从中导出的数据库

--collection -->您想要导出的集合

--type -->在我的例子中,导出类型为 CSV

--out -->要导出的文件名

--fields -->您想要导出的所有字段(如果是 CSV,请不要在逗号之间的两个字段名称之间添加空格)

--authenticationDatabase -->存储所有用户信息的数据库

For all those who are stuck with an error.

Let me give you guys a solution with a brief explanation of the same:-

command to connect:-

mongoexport --host your_host --port your_port -u your_username -p your_password --db your_db --collection your_collection --type=csv --out file_name.csv --fields all_the_fields --authenticationDatabase admin

--host --> host of Mongo server

--port --> port of Mongo server

-u --> username

-p --> password

--db --> db from which you want to export

--collection --> collection you want to export

--type --> type of export in my case CSV

--out --> file name where you want to export

--fields --> all the fields you want to export (don't give spaces in between two field name in between commas in case of CSV)

--authenticationDatabase --> database where all your user information is stored

挖个坑埋了你 2024-12-03 06:51:48

以下命令用于将集合导出为 CSV 格式。

注意:naag 是数据库,employee1_json 是集合。

mongoexport --db naag--collection employee1_json --type csv --out /home/orienit/work/mongodb/employee1_csv_op1

Below command used to export collection to CSV format.

Note: naag is database, employee1_json is a collection.

mongoexport --db naag--collection employee1_json --type csv --out /home/orienit/work/mongodb/employee1_csv_op1
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文