繁体   English   中英

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

[英]Retrieving one document with MongoDB MongoClient in Java 8

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

连接很好,我可以查看收藏集等。

我的问题行如下:

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但没有运气时,我感到很困惑。

编译器会确切告诉您问题出在哪里-请尝试以下操作:

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

记住, find返回FindIterable ,因此您需要调用first()来获取Document

我还建议您阅读教程-您将学到很多东西。

您不需要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<>());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM