How to mongoexport with one field

≯℡__Kan透↙ 提交于 2019-12-08 08:41:10

问题


i have a few fields in my collection at the mongoDB. i have tried exported out everything. which looking like this

{"_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\"",

but now i want to export just a single field which is the 'message' from the 'comments_data' from the collection.

i tried using this mongoexport --db sDB --collection sTest --fields data.comments_data --out test88.json

but when i check my exported file, it just contains something like this

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

which is something not i have expected. i just want something like "message":"Happy bday..Godbless you..." but when i query out at the mongoshell with db.sTest.find({}, {comments_data:1, _id:0})i can roughly get what i want.


回答1:


If this ...

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

... selects the data you are interested in then the equivalent mongoexport command is:

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

Note: this uses --type csv because, according to the docs, use of the JSON output format causes MongoDB to export all fields in the selected sub document ...

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.

If you must have JSON format and limit your output to a single field then I think you'll need to write the reduced documents to a separate collection and export that collection, as per this answer.



来源:https://stackoverflow.com/questions/48296724/how-to-mongoexport-with-one-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!