gpt4 book ai didi

MongoDB 的 Java 驱动程序 : Can't resolve function toJson()

转载 作者:行者123 更新时间:2023-12-01 09:06:43 25 4
gpt4 key购买 nike

我根据链接编写了以下代码 http://mongodb.github.io/mongo-java-driver/3.4/driver/getting-started/quick-start/ (参见标题“查找集合中的所有文档”):

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;

public class Main {
public static void main(String[] args) {
MongoClient mongoClient = new MongoClient();
MongoDatabase database = mongoClient.getDatabase("test");
MongoCollection collection = database.getCollection("test");
MongoCursor cursor = collection.find().iterator();
try {
while(cursor.hasNext()) {
System.out.println(cursor.next().toJson());
}
} finally {
cursor.close();
}
}
}

但是,我收到一个错误,函数 toJson() 无法解析。你知道我如何使这段代码工作吗?

最佳答案

问题是缺少类型。光标的 next 方法返回集合的类型。下面的示例使用 bson 的 Document 类型。

import org.bson.Document;

MongoDatabase database = mongoClient.getDatabase("test");
MongoCollection<Document> collection = database.getCollection("test");
MongoCursor<Document> cursor = collection.find().iterator();
try {
while(cursor.hasNext()) {
System.out.println(cursor.next().toJson());
}
} finally {
cursor.close();
}

关于MongoDB 的 Java 驱动程序 : Can't resolve function toJson(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41208310/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com