开发者

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

开发者 https://www.devze.com 2023-03-21 06:52 出处:网络
开发者_如何转开发findOne() results in pretty-print json object. find() results in jarbled json object.

开发者_如何转开发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?


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 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.


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.


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


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

  • Developper site : http://tylerbrock.github.io/mongo-hacker/
  • Github repos : https://github.com/TylerBrock/mongo-hacker
0

精彩评论

暂无评论...
验证码 换一张
取 消