在Java上通过ID获取MongoDB文档

时间:2016-10-08 16:32:31

标签: java mongodb search

我之前在MongoDB中添加了一组ID文档。

然后我尝试从ID获取文档。

String idString = "57f8f50977c8a5b8757f261a";
BasicDBObject whereQuery = new BasicDBObject();
whereQuery.put("_id", idString);
DBCursor cursor = table.find(whereQuery);            
if(cursor.hasNext())
{
 System.out.println("FOUND!" + cursor.next());
}

我得到零结果。

但是,如果我打电话给另一个领域 它工作并返回给我文件。

BasicDBObject whereQuery = new BasicDBObject();
whereQuery.put("datachain", "AA");
DBCursor cursor = table.find(whereQuery);
if(cursor.hasNext())
{
System.out.println("FOUND!" + cursor.next());
}

FOUND!{ "_id" : { "$oid" : "57f8f50977c8a5b8757f261b"} , "datachain" : "AA" , "createdDate" : { "$date" : "2016-10-08T13:30:49.588Z"}}

我做错了什么?为什么我无法通过ID查找文档? 日Thnx!

UPD:     BasicDBObject whereQuery = new BasicDBObject();     whereQuery.put(" _id",new ObjectId(" 57f8f50977c8a5b8757f261a"));     DBCursor cursor = table.find(whereQuery);

同样,没有结果。

1 个答案:

答案 0 :(得分:2)

您必须将idString作为ObjectId传递。

whereQuery.put("_id", new ObjectId(idString));