mongocollection java,在MongoCollection< Document>中找到

"在MongoDB中尝试通过_id字段查找用户时遇到了类型转换错误。错误发生在将FindIterableImpl对象强制转换为Document对象。解决方法是使用过滤器创建查询,例如:`myDoc = collection.find(eq("_id", "test")).first();` 这将找到_id字段为'test'的文档,并打印其JSON表示。"
摘要由CSDN通过智能技术生成

I have a MongoCollection in which I assign a collection.

I'm trying to find a user by his id.

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

with that I'm getting an error

java.lang.ClassCastException: com.mongodb.FindIterableImpl cannot be

cast to org.bson.Document

When I try

BasicDBObject query = new BasicDBObject();

BasicDBObject fields = new BasicDBObject("_id", username);

usersCollection.find(query, fields);

I'm getting an error

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

解决方案

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 collection = database.getCollection("mycoll");

myDoc = collection.find(eq("_id", "test")).first();

System.out.println(myDoc.toJson());

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值