mongoexport 导出时 去掉 _id字段
mongoexport 导出时可以规定需要导出的字段 mongodb
官方文档介绍:
--fields=<field1[,field2]>, -f=<field1[,field2]>
Specifies a field or fields to include in the export. Use a comma separated list of fields to specify multiple fields.
If any of your field names include white space, use quotation marks to enclose the field list. For example, if you wished to export two fields, phone and user number, you would specify --fields "phone,user number".
For csv output formats, mongoexport includes only the specified field(s), and the specified field(s) can be a field within a sub-document.
For JSON output formats, mongoexport includes only the specified field(s) and the _id field, and if the specified field(s) is a field within a sub-document, the mongoexport includes the sub-document with all its fields, not just the specified field within the document.
See: Export Data in CSV Format using --fields option for sample usage.
但我的业务是导出所有字段,除了_id,用 --fields
太过麻烦,一是我也不知道有什么字段;二是在字段很多的情况下就难处理;
查了一下,在https://stackoverflow.com/questions/12976145/mongoexport-without-id-field 找到了答案:
mongoexport --db db_name --collection collection_name | sed '/"_id":/s/"_id":[^,]*,//' > file_name.json
但是我的环境是window,这里出现了问题,你需要把sed
添加到环境变量中,在安装了git情况下,可以无需再安装sed,在D://yourGitPath/usr/bin
中有sed.exe
,因此只需要把D://yourGitPath/usr/bin
加入环境变量即可。
同时,在windows环境下sed命令有单引号运行没有作用,在这篇博客上找到了我怎么尝试都没有用的原因:https://blog.csdn.net/kowity/article/details/1750569
最终解决:
我将单引号变为了双引号,在单引号里面内容的双引号用了\
转义:
mongoexport --dbdb_name --collection collection_name | sed "/\"_id\":/s/\"_id\":[^,]*,//"