在 Mongo 中,如何美化打印结果,使. find()看起来像. findOne()

findOne()产生漂亮的打印 json 对象。

find()生成 json 对象。

在 mongo shell 中显示时,如何使 find()findOne()相同?

47221 次浏览

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.

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()

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

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()

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.