How to export collection to CSV in MongoDB?

前端 未结 11 1574
刺人心
刺人心 2020-12-12 11:52

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

mongoexport --host localhost --db dbname --collection name --type=csv          


        
11条回答
  •  失恋的感觉
    2020-12-12 12:25

    @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
    

提交回复
热议问题