gpt4 book ai didi

java - 在 Java 8 中使用 MongoDB MongoClient 检索一个文档

转载 作者:行者123 更新时间:2023-11-29 08:32:17 25 4
gpt4 key购买 nike

我是 Java 和 MongoDB 的新手,尽管花了几个小时弄乱了这个,但我无法使用 Java Mongodb-Driver 客户端 3.2.2 轻松检索简单的文档。

连接很好,我可以查看 Collection 等。

我的问题行如下:

Document profile = collection.find(new Document("_id", 10));

但是当我编译时出现以下错误:

Java:incompatible types: com.mongodb.client.Finditerable<org.bson.Document> cannot be converted to org.bson.Document

现在我可以解决这个问题,因为在 Stack Overflow 上进行一些谷歌搜索会生成以下代码,该代码有效但对我来说似乎不必要地复杂:

Document profile = collection.find(new Document("_id", 10)).projection(Projections.fields(Projections.include("firstName")))).first();

当我尝试将类型更改为 BasicDBObject 但没有成功时,我感到很困惑。

最佳答案

你不需要projection,只是

Document profile = collection.find(new Document("_id", 10)).first();

交替...

import static com.mongodb.client.model.Filters.eq;
// other code removed
Document profile = collection.find(eq("_id", 10)).first();

如您所见,find 返回 FindIterable ,而不是直接使用一个或多个 Document 对象。这起初很烦人,但非常强大和有用。

要在多个条件下进行过滤,这就是我所做的:

List<Bson> filters = new ArrayList<>();
filters.add(eq("department", dept));
filters.add(gt("salary", threshold));
// etc.
List<Document> docs = collection.find(and(filters)).into(new ArrayList<>());

关于java - 在 Java 8 中使用 MongoDB MongoClient 检索一个文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46917771/

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