I want to pretty print the results of a mongodb find() to a file. The json object is too large so i am not able to view the entire object with the shell window size.
Is there a way to 'pretty' print the results to a file from the shell?
The shell provides some nice but hidden features because it's an interactive environment.
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
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.
$ mongo --quiet dbname --eval 'printjson(db.collection.find().toArray())' > output.json