In Mongo, how to display results when executing .find () is the same as .findOne ()

findOne() outputs a json object with pretty typed text.

find() results in a jarbled json object.

How can I make find() same as findOne() when it appears in mongo shell?

+62
database mongodb
Jul 20 '11 at 1:29
source share
4 answers

If you are using a script using javascript, you can use dcrosta's answer. But if you want to print beautifully directly on the mongo interactive shell, you need to add pretty () to your find () queries.

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

+134
Jul 20 '11 at 11:27
source share

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

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

However, note that unlike the default output find() , which shows the first 10 objects, then you can choose whether to continue the repeat or not, forEach() will iterate the entire result set. Thus, if your query returns a lot of results, this may take some time and may not be very useful. limit() is your friend here.

+19
Jul 20 '11 at 1:40
source share

The correct answer is already provided with .pretty() .

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

 db.foo.find().toArray() 
+2
Nov 16 '16 at 21:20
source share

The convenient mongo-hacker mango shell amp ( http://mongodb-tools.com/tool/mongo-hacker/ ) allows you to do this and more fancy things.

+1
Mar 24 '16 at 18:53
source share



All Articles