MongoDB - mongoexport all objects in nested array

a 夏天 提交于 2019-11-29 08:16:54

MongoExport

To export the property whose value is array of object then unwind the array to make single document and store in new collection then export that collection.

For Instance

Database : abc collection : xyz

db.xyz.aggregate([
   {$unwind: "$field_array"},
   {$project: { _id:0,field_id:"$_id",Innerfield: "$field_array", "field_1": 1,"field_2":1}},
   {$out: "aggregate_xyz"}
])

MongoExport syntax

mongoexport --host <hostname> --db <Database Name> --collection <collection Name> --csv --fields fieldname1,fieldname2 --out fileName.csv

Example : Export in CSV Format

mongoexport --host localhost --db abc --collection aggregate_xyz --csv --fields field_id,field_1,field_2,Innerfield.sub_field_1,Innerfield.sub_field_2 --out important.csv

Example : Export in JSON Format

mongoexport --host localhost --db abc --collection aggregate_xyz --fields field_id,field_1,field_2,Innerfield.sub_field_1,Innerfield.sub_field_2 --out important.json

To know more please visit

$unwind

https://docs.mongodb.org/v3.0/reference/operator/aggregation/unwind/

$out

https://docs.mongodb.org/v3.0/reference/operator/aggregation/out/

$project

https://docs.mongodb.org/v3.0/reference/operator/aggregation/project/

It seems that mongoexport can not export all elements of array, unless you specify all of them with index one by one. Of course this is unrealistic.
So you can split the array and save data into a temporary collection, then export from this new collection.

db.collection_name.aggregate([ {
    $match : {
        "field_array.sub_field_1" : {
            $gte : "some_value_1",
            $lt : "some_value_2"
        }
    }
}, {
    $project : {
        _id : 0,
        field_array : 1
    }
}, {
    $unwind : "$field_array"
}, {
    $out : "forcsv"
} ]);

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