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

viper picture viper · Oct 28, 2012 · Viewed 109.3k times · Source

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 window size.

Answer

Asya Kamsky picture Asya Kamsky · Oct 28, 2012

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