Pretty print in MongoDB shell as default

MongodbCommand Line-InterfaceMongo Shell

Mongodb Problem Overview


Is there a way to tell Mongo to pretty print output? Currently, everything is output to a single line and it's difficult to read, especially with nested arrays and documents.

Mongodb Solutions


Solution 1 - Mongodb

(note: this is answer to original version of the question, which did not have requirements for "default")

You can ask it to be pretty.

db.collection.find().pretty()

Solution 2 - Mongodb

You can add

DBQuery.prototype._prettyShell = true

to your file in $HOME/.mongorc.js to enable pretty print globally by default.

Solution 3 - Mongodb

(note: this is answer to the updated question)

You can just do this on the CLI:

echo DBQuery.prototype._prettyShell = true >> ~/.mongorc.js

And it's always going to output pretty results.

Solution 4 - Mongodb

Since it is basically a javascript shell, you can also use toArray():

db.collection.find().toArray()

However, this will print all the documents of the collection unlike pretty() that will allow you to iterate. Refer: http://docs.mongodb.org/manual/reference/method/cursor.toArray/

Solution 5 - Mongodb

Oh so i guess .pretty() is equal to:

db.collection.find().forEach(printjson);

Solution 6 - Mongodb

Give a try to Mongo-hacker(node module), it alway prints pretty. https://github.com/TylerBrock/mongo-hacker

More it enhances mongo shell (supports only ver>2.4, current ver is 3.0), like

  • Colorization
  • Additional shell commands (count documents/count docs/etc)
  • API Additions (db.collection.find({ ... }).last(), db.collection.find({ ... }).reverse(), etc)
  • Aggregation Framework

I am using for while in production env, no problems yet.

Solution 7 - Mongodb

Got to the question but could not figure out how to print it from externally-loaded mongo. So:

This works is for console: and is prefered in console, but does not work in external mongo-loaded javascript:

db.quizes.find().pretty()

This works in external mongo-loaded javscript:

db.quizes.find().forEach(printjson)

Solution 8 - Mongodb

Check this out:

db.collection.find().pretty()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionraffianView Question on Stackoverflow
Solution 1 - MongodbSergio TulentsevView Answer on Stackoverflow
Solution 2 - Mongodbstaackuser2View Answer on Stackoverflow
Solution 3 - MongodbBhanu ChawlaView Answer on Stackoverflow
Solution 4 - MongodbAafreen SheikhView Answer on Stackoverflow
Solution 5 - MongodbGoffView Answer on Stackoverflow
Solution 6 - MongodbGaurav GandhiView Answer on Stackoverflow
Solution 7 - MongodbWitold KaczurbaView Answer on Stackoverflow
Solution 8 - MongodbMohammad HeydariView Answer on Stackoverflow