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