如何用一个字段进行mongoexport

How to mongoexport with one field

我在 mongoDB 的 collection 中有几个字段。 我已经尝试导出所有内容。 看起来像这样

{"_id":{"$oid":"5a5ef05dbe83813f55141a51"},"comments_data":{"id":"211","comments":{"paging":{"cursors":{"after":"WzZANVFV4TlRVME5qUXpPUT09","before":"WTI5dEF4TlRVNE1USTVNemczTXpZAMk56YzZANVFV4TlRBMU9ERTFNQT09"}},"data":[{"created_time":"2018-01-04T09:29:09+0000","message":"Super","from":{"name":"M Mun","id":"1112"},"id":"1111"},{"created_time":"2018-01-07T22:25:08+0000","message":"Happy bday..Godbless you...","from":{"name":"L1","id":"111"},"id":"1111"},{"created_time":"2018-01-10T00:22:00+0000","message":"Nelson ","from":{"name":"Boon C","id":"1111"},"id":"10111"},{"created_time":"2018-01-10T01:07:19+0000","message":"Thank to SingTel I like to","from":{"name":"Sarkar WI","id":"411653482605703"},"id":"10155812413346677_10155825869201677"}]}},"post_id":"28011986676_10155812413346677","post_message":"\"Usher in the New Year with deals and rewards that will surely perk you up, exclusively for Singtel customers. Find out more at singtel.com/rewards\"",

但现在我只想导出一个字段,即 'message' 来自 'comments_data' 来自 collection.

我试过用这个mongoexport --db sDB --collection sTest --fields data.comments_data --out test88.json

但是当我检查导出的文件时,它只包含类似这样的内容

{"_id":{"$oid":"5a5ef05dbe83813f55141a51"}}

这出乎我的意料。 我只想要 "message":"Happy bday..Godbless you..." 但是当我用 db.sTest.find({}, {comments_data:1, _id:0}) 在 mongoshell 上查询时,我可以大致得到我想要的东西。

如果这...

db.sTest.find({}, {'comments_data.message':1, _id:0})

... 选择您感兴趣的数据然后等效的 mongoexport 命令是:

mongoexport --db sDB --collection sTest --fields 'comments_data.message' --type csv --out test88.csv

注意:这使用 --type csv,因为根据 the docs,使用 JSON 输出格式会导致 MongoDB 导出所选子文档中的所有字段。 ..

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.

如果您必须使用 JSON 格式并将输出限制为单个字段,那么我认为您需要将精简文档写入单独的集合并导出 that 集合,根据 .