【问题标题】:Is there a way to Convert a FindIterable<Document> into JSONArray string?有没有办法将 FindIterable<Document> 转换为 JSONArray 字符串?
【发布时间】:2018-09-04 14:56:03
【问题描述】:

我得到了这样的东西

MongoClient mongoClient = new MongoClient();
MongoDatabase database = mongoClient.getDatabase(db);
MongoCollection<Document> collection = database.getCollection(col);

FindIterable<Document> results = collection.find();

我可以使用以下方法获取 JSONArray 字符串:

JSON.serialize(results)

但在最新版本的 mongodb 驱动程序中已弃用。

在 MongoDB shell 中我可以使用:

db.$.find().toArray();

但我在 Java 的驱动程序中没有找到类似的东西。

我使用 List 并遍历光标解决了问题。

MongoCursor<Document> cursor = results.iterator();
List<String> list = new ArrayList<String>(); 

while(cursor.hasNext())
    list.add(cursor.next().toJson());

return list.toString();

请随意提出更好的解决方案。

【问题讨论】:

  • 您正在做的事情(在每个Document 上迭代和调用toJson())是使用JSON 实用程序类的推荐替代品。来自the commit which deprecated that class:“应用程序应该用 JsonReader、JsonReader 和包装它们的 BasicDBObject 上的 toJson/parse 方法替换它的使用。”。

标签: java json mongodb


【解决方案1】:

在 find 迭代器上使用 spliterator(),然后流式传输,映射到 String 并收集:

StreamSupport.stream(collection.find().spliterator(), false)
        .map(Document::toJson)
        .collect(Collectors.joining(", ", "[", "]"))

请注意,并行流对 mongo 结果不起作用,因此请将 parallel 标志保留为 false

【讨论】:

  • StreamSupport.stream(...).collect(...) 是否保留初始 collection.find(...) 顺序/排序?
  • @bastienenjalbert 是的
【解决方案2】:

注意this answer 可能导致资源泄漏,因为在collection.find().spliterator() 内部创建的迭代器永远不会关闭,它需要关闭才能将连接返回到连接池。 要解决这个问题,您需要按以下方式进行:

try (MongoCursor<Document> cursor = collection.find().iterator()) {
    return StreamSupport.stream(Spliterators.spliteratorUnknownSize(cursor,0), false)
                        .map(Document::toJson)
                        .collect(Collectors.toList())
}

或者不使用流:

return collection.find()
                 .map(Document::toJson)
                 .into(new ArrayList<>());

在这种情况下,资源 (MongoCursor) 也已正确关闭。

【讨论】:

    猜你喜欢
    • 2023-01-30
    • 1970-01-01
    • 2015-03-29
    • 2011-09-21
    • 2021-04-04
    • 2021-03-03
    • 2020-12-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多