In Mongo, how do I pretty-print results so .find() looks like .findOne()

MongodbDatabase

Mongodb Problem Overview


findOne() results in pretty-print json object.

find() results in jarbled json object.

How can I make find() the same as findOne(), when it comes to display in the mongo shell?

Mongodb Solutions


Solution 1 - Mongodb

If you are scripting using javascript, you can use dcrosta's answer. But if you want to pretty print directly on the mongo interactive shell, you have to append pretty() to your find() queries.

Type on the shell: db.yourcollection.find().pretty()

Solution 2 - Mongodb

The cursor object returned by find() supports forEach(), so you can use:

db.foo.find().forEach(printjson)

However note that, unlike the default output of find() which shows the first 10 objects then lets you choose whether to continue iterating or not, forEach() will iterate the entire result set. Thus if your query returns many results, this may take a while and may not be terribly helpful. limit() is your friend here.

Solution 3 - Mongodb

It may not have been available at the time the question was asked, but to make the default output for all find() queries to be pretty, I use:

DBQuery.prototype._prettyShell = true

I also add the following:

DBQuery.prototype.ugly = function() {
    this._prettyShell = false;
    return this;
}

which enables me to uglify the results of a single find() query using:

db.mycollection.find().ugly()

I typically add both prototype declarations into my ~/.mongorc.js file so they are available in all mongo cli shells.

Solution 4 - Mongodb

The correct answer is already provided with the use of .pretty().

However just as a side note, you can also call .toArray() on the cursor to get the documents as javascript array of JSON.

db.foo.find().toArray()

Solution 5 - Mongodb

The handy mongo-shell enhancer mongo-hacker (http://mongodb-tools.com/tool/mongo-hacker/) will allow you to do that and more fancy things.

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
QuestionTIMEXView Question on Stackoverflow
Solution 1 - MongodbRohanView Answer on Stackoverflow
Solution 2 - MongodbdcrostaView Answer on Stackoverflow
Solution 3 - MongodbDavid WeinraubView Answer on Stackoverflow
Solution 4 - MongodbRahul KumarView Answer on Stackoverflow
Solution 5 - MongodbFlorianView Answer on Stackoverflow