【问题标题】:How can I print document in cursor.ForEach?如何在 cursor.ForEach 中打印文档?
【发布时间】:2016-01-30 18:00:29
【问题描述】:

我在某个集合上定义了一些简单的光标作为 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)})

它只打印这个:

[对象对象]

如果我修改一个循环来选择一些简单的属性,它会起作用:

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

虽然如果我将其更改为打印分数,它会打印:

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

mongodb shell有没有打印json文档的功能?

【问题讨论】:

    标签: mongodb mongodb-query mongo-shell


    【解决方案1】:

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

    如果是手动消费光标,需要使用printjson函数

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

    或以下带有过滤器的表达式

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

    【讨论】:

    • 你也可以使用函数pretty:db.collection.find({}, { "scores": 1, "_id": 0 }).pretty()
    • 虽然这篇文章有点老:你也可以使用下面的符号db.collection.find().forEach(function(record){printjson(record.field)})
    • 这仅适用于您想要漂亮地打印文档中的单个字段的情况。 @托比亚斯
    【解决方案2】:

    如果您的结果集很小,您可以将它放在一个集合中,然后对其进行迭代。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-02
      • 2015-08-07
      相关资源
      最近更新 更多