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.
pretty() method is used to configure the cursor to display results in an easy-to-read format.
In mongo shell: db. collection. findOne() prints the returned document in a well formatted JSON. To print the result (one or more documents) of find() in a formatted way, use db.
You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});
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
Since you are doing this on a terminal and just want to inspect a record in a sane way, you can use a trick like this:
mongo | tee somefile
Use the session as normal - db.collection.find().pretty()
or whatever you need to do, ignore the long output, and exit. A transcript of your session will be in the file tee
wrote to.
Be mindful that the output might contain escape sequences and other garbage due to the mongo shell expecting an interactive session. less
handles these gracefully.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With