在MongoCollection 中找到

我有一个MongoCollection ,我在其中分配了一个集合。 我想通过他的身份找到一个用户。

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

我得到了一个错误

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

当我尝试

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

我收到了一个错误

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

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

 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()); 

您的问题是您假设find()方法返回单个Document 。 它没有。 它返回一个列表。

在MongoDB 2 Java驱动程序中, DBCollection类上有一个名为findOne() 。 在MongoDB 3 Java驱动程序API中, findOne()方法不存在。 因此,用于查找一个文档的新代码也变得类似于此:

 collection.find(eq("_id", 3)).first() 

其中eq("_id", 3)在您的集合中称为filter。

做这个 –

  MongoClient client = new MongoClient(); DBObject resultObject = new BasicDBObject("_id", username); MongoDatabase database = client.getDatabase("DBNAME"); MongoCollection collection = database.getCollection("COLLECTION_NAME"); DBObject dbObject = new BasicDBObject("_id", username); resultObject = collection.find(dbObject).next(); String result = resultObject.get(YOUR_COLOUM_NAME);