6

I've defined some simple cursor as find() on some collection.

cursor = db.students.find()

Student has following schema:

"_id" : 19,
"name" : "Gisela Levin",
"scores" : [
        {
                "type" : "exam",
                "score" : 44.51211101958831
        },
        {
                "type" : "quiz",
                "score" : 0.6578497966368002
        },
        {
                "type" : "homework",
                "score" : 93.36341655949683
        },
        {
                "type" : "homework",
                "score" : 49.43132782777443
        }
]

I want to iterate cursor and print a document. I try like that:

cursor.forEach(function(o){print(o)})

It prints only this:

[object Object]

If I modify a loop to select some simple property it works:

cursor.forEach(function(o){print(o._id)})

Though if I change it to print scores it prints this:

[object Object],[object Object],[object Object],[object Object]

Is there any function to print a json document in mongodb shell?

styvane
  • 59,869
  • 19
  • 150
  • 156
Arkadiusz Kałkus
  • 17,101
  • 19
  • 69
  • 108

2 Answers2

16

I am not sure why the pretty can't be applied to your case.

If you are consuming the cursor manually, you need to use the printjson function

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

or the following with filter expression

db.collection.find({}, { "scores": 1, "_id": 0 }).forEach(printjson)
styvane
  • 59,869
  • 19
  • 150
  • 156
  • You could also use the function `pretty`: `db.collection.find({}, { "scores": 1, "_id": 0 }).pretty()`. – Alex Oct 30 '15 at 11:52
  • 3
    Although this post is a bit older: You could also use the following notation `db.collection.find().forEach(function(record){printjson(record.field)})` – Tobias Oct 13 '17 at 11:14
  • This only apply if the you want to pretty print a single field in the document. @Tobias – styvane Oct 13 '17 at 14:55
0

If your result set is small you can out it in a collection and then iterate over it.

List<org.bson.Document> resultList = (List<org.bson.Document>) mongoCollection.find()
        .into(new ArrayList<org.bson.Document>());
resultList.forEach(doc -> printJson(doc));

And printJson is

public static void printJson(org.bson.Document doc) {
    JsonWriter jsonWriter = new JsonWriter(new StringWriter(), new JsonWriterSettings(JsonMode.SHELL, true));
    new DocumentCodec().encode(jsonWriter, doc,
            EncoderContext.builder().isEncodingCollectibleDocument(true).build());
    System.out.println(jsonWriter.getWriter());
    System.out.flush();
}
Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289