Dump Mongo Collection into JSON format

后端 未结 5 873
小蘑菇
小蘑菇 2020-12-04 07:10

Is there any way to dump mongo collection into json format? Either on the shell or using java driver.I am looking for the one with best performance.

相关标签:
5条回答
  • 2020-12-04 07:27

    From the Mongo documentation:

    The mongoexport utility takes a collection and exports to either JSON or CSV. You can specify a filter for the query, or a list of fields to output

    Read more here: http://www.mongodb.org/display/DOCS/mongoexport

    0 讨论(0)
  • 2020-12-04 07:42

    If you want to dump all collections, run this command:

    mongodump -d {DB_NAME}   -o /tmp 
    

    It will generate all collections data in json and bson extensions into /tmp/{DB_NAME} directory

    0 讨论(0)
  • 2020-12-04 07:49

    Mongo includes a mongoexport utility (see docs) which can dump a collection. This utility uses the native libmongoclient and is likely the fastest method.

    mongoexport -d <database> -c <collection_name>
    

    Also helpful:

    -o: write the output to file, otherwise standard output is used (docs)

    --jsonArray: generates a valid json document, instead of one json object per line (docs)

    --pretty: outputs formatted json (docs)

    0 讨论(0)
  • 2020-12-04 07:51

    Here's mine command for reference:

    mongoexport --db AppDB --collection files --pretty --out output.json
    

    On Windows 7 (MongoDB 3.4), one has to move the cmd to the place where mongod.exe and mongo.exe file resides => C:\MongoDB\Server\3.4\bin else it won't work saying it does not recongnize mongoexport command.

    0 讨论(0)
  • 2020-12-04 07:52

    Use mongoexport/mongoimport to dump/restore a collection:

    Export JSON File:

    mongoexport --db <database-name> --collection <collection-name> --out output.json

    Import JSON File:

    mongoimport --db <database-name> --collection <collection-name> --file input.json

    WARNING mongoimport and mongoexport do not reliably preserve all rich BSON data types because JSON can only represent a subset of the types supported by BSON. As a result, data exported or imported with these tools may lose some measure of fidelity.

    Also, http://bsonspec.org/

    BSON is designed to be fast to encode and decode. For example, integers are stored as 32 (or 64) bit integers, so they don't need to be parsed to and from text. This uses more space than JSON for small integers, but is much faster to parse.

    In addition to compactness, BSON adds additional data types unavailable in JSON, notably the BinData and Date data types.

    0 讨论(0)
提交回复
热议问题