在MongoCollection< Document>中找到 [英] find in MongoCollection<Document>

查看:1588
本文介绍了在MongoCollection< Document>中找到的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 MongoCollection< Document> ,我在其中分配了一个集合。
我正在尝试通过他的ID找到用户。

I have a MongoCollection<Document> in which I assign a collection. I'm trying to find a user by his id.

user = (Document) usersCollection.find(new Document("_id", username));

我收到错误

java.lang.ClassCastException:com.mongodb.FindIterableImpl不能
强制转换为org.bson.Document

java.lang.ClassCastException: com.mongodb.FindIterableImpl cannot be cast to org.bson.Document

当我尝试

    BasicDBObject query = new BasicDBObject(); 
    BasicDBObject fields = new BasicDBObject("_id", username);
    usersCollection.find(query, fields);

我收到错误


MongoCollection类型中的方法find(Bson,Class)不适用于参数(BasicDBObject,BasicDBObject)

The method find(Bson, Class) in the type MongoCollection is not applicable for the arguments (BasicDBObject, BasicDBObject)


推荐答案

尝试创建一个过滤器以传递给 find() 方法获取集合中的文档子集。例如,要查找 _id 字段的值为 test 的文档,您将执行以下操作:

Try to create a filter to pass to the find() method to get a subset of the documents in your collection. For example, to find the document for which the value of the _id field is test, you would do the following:

import static com.mongodb.client.model.Filters.*;

MongoClient client = new MongoClient();
MongoDatabase database = client.getDatabase("mydb");
MongoCollection<Document> collection = database.getCollection("mycoll");
myDoc = collection.find(eq("_id", "test")).first();
System.out.println(myDoc.toJson());

这篇关于在MongoCollection&lt; Document&gt;中找到的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆