Is there a way to 'pretty' print MongoDB shell output to a file?

前端 未结 10 1833
余生分开走
余生分开走 2020-11-27 09:38

Specifically, I want to print the results of a mongodb find() to a file. The JSON object is too large so I\'m unable to view the entire object with the shell wi

相关标签:
10条回答
  • 2020-11-27 10:23

    Put your query (e.g. db.someCollection.find().pretty()) to a javascript file, let's say query.js. Then run it in your operating system's shell using command:

    mongo yourDb < query.js > outputFile

    Query result will be in the file named 'outputFile'.

    By default Mongo prints out first 20 documents IIRC. If you want more you can define new value to batch size in Mongo shell, e.g.

    DBQuery.shellBatchSize = 100.

    0 讨论(0)
  • 2020-11-27 10:37

    Using print and JSON.stringify you can simply produce a valid JSON result.
    Use --quiet flag to filter shell noise from the output.
    Use --norc flag to avoid .mongorc.js evaluation. (I had to do it because of a pretty-formatter that I use, which produces invalid JSON output) Use DBQuery.shellBatchSize = ? replacing ? with the limit of the actual result to avoid paging.

    And finally, use tee to pipe the terminal output to a file:

    // Shell:
    mongo --quiet --norc ./query.js | tee ~/my_output.json
    
    // query.js:
    DBQuery.shellBatchSize = 2000;
    function toPrint(data) {
      print(JSON.stringify(data, null, 2));
    }
    
    toPrint(
      db.getCollection('myCollection').find().toArray()
    );
    

    Hope this helps!

    0 讨论(0)
  • 2020-11-27 10:37

    Using this answer from Asya Kamsky, I wrote a one-line bat script for Windows. The line looks like this:

    mongo --quiet %1 --eval "printjson(db.%2.find().toArray())" > output.json

    Then one can run it:

    exportToJson.bat DbName CollectionName

    0 讨论(0)
  • 2020-11-27 10:38

    Also there is mongoexport for that, but I'm not sure since which version it is available.

    Example:

    mongoexport -d dbname -c collection --jsonArray --pretty --quiet --out output.json
    
    0 讨论(0)
提交回复
热议问题