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

前端 未结 10 1941
余生分开走
余生分开走 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: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!

提交回复
热议问题