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

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

    The shell provides some nice but hidden features because it's an interactive environment.

    When you run commands from a javascript file via mongo commands.js you won't get quite identical behavior.

    There are two ways around this.

    (1) fake out the shell and make it think you are in interactive mode

    $ mongo dbname << EOF > output.json
    db.collection.find().pretty()
    EOF
    

    or
    (2) use Javascript to translate the result of a find() into a printable JSON

    mongo dbname command.js > output.json
    

    where command.js contains this (or its equivalent):

    printjson( db.collection.find().toArray() )
    

    This will pretty print the array of results, including [ ] - if you don't want that you can iterate over the array and printjson() each element.

    By the way if you are running just a single Javascript statement you don't have to put it in a file and instead you can use:

    $ mongo --quiet dbname --eval 'printjson(db.collection.find().toArray())' > output.json
    

提交回复
热议问题