Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 578
viper Avatar asked Oct 27 '12 22:10

viper


People also ask

What is the use of pretty () method in MongoDB?

pretty() method is used to configure the cursor to display results in an easy-to-read format.

How do I print a MongoDB database?

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.

How do I print a specific field in MongoDB?

You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});


2 Answers

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 
like image 89
Asya Kamsky Avatar answered Oct 14 '22 13:10

Asya Kamsky


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.

like image 44
Falcon Momot Avatar answered Oct 14 '22 12:10

Falcon Momot