如何在cursor.ForEach中打印文档?

时间:2015-10-30 10:28:27

标签: mongodb mongodb-query mongo-shell

我在一些集合上将一些简单的游标定义为find()。

cursor = db.students.find()

学生有以下架构:

"_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
        }
]

我想迭代光标并打印文档。我这样试试:

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

它仅打印:

  

[object Object]

如果我修改一个循环来选择一些简单的属性就可以了:

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

虽然如果我将其更改为打印分数,则打印出来:

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

是否有任何函数可以在mongodb shell中打印json文档?

2 个答案:

答案 0 :(得分:8)

我不确定为什么pretty无法应用于您的案例。

如果您手动使用光标,则需要使用printjson功能

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

或以下过滤表达式

db.collection.find({}, { "scores": 1, "_id": 0 }).forEach(printjson)

答案 1 :(得分:0)

如果您的结果集很小,您可以在集合中将其输出,然后迭代它。

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

而且printJson是

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();
}
相关问题