我得到了类似这样的东西。
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驱动程序中没有找到类似的内容。
我使用一个列表并迭代游标来解决这个问题。
MongoCursor<Document> cursor = results.iterator();
List<String> list = new ArrayList<String>();
while(cursor.hasNext())
list.add(cursor.next().toJson());
return list.toString();
无论如何,欢迎提出更好的解决方案。
toJson()
)是使用JSON
实用程序类的推荐替代方法。从弃用该类的提交中可以看到:“应用程序应将其使用替换为JsonReader、JsonWriter以及包装它们的BasicDBObject上的toJson/parse方法。”。 - glytching