<Document> 使用 Java MongoDB 4.0.4 驱动程序使用块打印集合时出现编译错误



当使用Java MongoDB Driver 4.0.4,OpenJDK 11并按照MongoDB文档上的示例进行操作时,在使用findIterable.forEach(printBlock);时看到编译错误

看起来com.mongodb.Blockhttp://mongodb.github.io/mongo-java-driver/4.0/driver/tutorials/aggregation/也没有被弃用。

public String testLocal() {
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
MongoDatabase database = mongoClient.getDatabase("cord");
MongoCollection<Document> collection1 = database.getCollection("papers");
FindIterable<Document> findIterable = collection1.find(new Document());
findIterable.forEach(printBlock);
}
public Block<Document> printBlock = new Block<Document>() {
@Override
public void apply(final Document document) {
System.out.println(document.toJson());
}
};

错误:

[ERROR] /Projects/cord/src/main/java/com/engg/java/cord/services/PrimaryService_Local.java:
[24,30] incompatible types: com.mongodb.Block<org.bson.Document> cannot be converted
to java.util.function.Consumer<? super org.bson.Document>

文档显然已经过时了。如果你看一下 FindIterable 的 javadocs (http://mongodb.github.io/mongo-java-driver/4.0/apidocs/mongodb-driver-sync/com/mongodb/client/FindIterable.html(您将看到forEach继承自java.lang.Iterable,将Consumer作为参数,而不是Block

因此,将您的 printBlock 声明替换为:

public Consumer<Document> printBlock = document -> System.out.println(document.toJson());

。一切都会好起来的。

在mtj和Mongodb支持的帮助下,添加工作代码块。

public String testLocal() {
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
MongoDatabase database = mongoClient.getDatabase("cord");
MongoCollection<Document> collection1 = database.getCollection("papers");
FindIterable<Document> findIterable = collection1.find(new Document());
findIterable.forEach((Consumer<Document>)  d -> System.out.println( d.toJson())); 
}

public Consumer<Document> printBlock = document -> System.out.println(document.toJson());
public String testLocal() {
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
MongoDatabase database = mongoClient.getDatabase("cord");
MongoCollection<Document> collection1 = database.getCollection("papers");
FindIterable<Document> findIterable = collection1.find(new Document());
findIterable.forEach(printBlock);
}

或参考 https://jira.mongodb.org/browse/DOCS-13638

public String testLocal() {
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
MongoDatabase database = mongoClient.getDatabase("cord");
MongoCollection<Document> collection1 = database.getCollection("papers");
FindIterable<Document> findIterable = collection1.find(new Document());
findIterable.forEach(printBlock);
}
Consumer<Document> printBlock = new Consumer<Document>() {
public void accept(final Document doc) {
System.out.println(doc.toJson());
};
};

最新更新