【问题标题】:Get MongoDB document by ID on Java在 Java 上按 ID 获取 MongoDB 文档
【发布时间】:2017-02-17 11:39:37
【问题描述】:

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

然后我尝试从 ID 获取 Document。

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 找到文件? 谢谢!

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

相同,没有结果。

【问题讨论】:

  • 你需要把你的String变成ObjectId

标签: java mongodb search


【解决方案1】:

您必须将 idString 作为 ObjectId 传递。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-19
    • 1970-01-01
    • 2020-12-27
    • 1970-01-01
    • 1970-01-01
    • 2012-12-11
    相关资源
    最近更新 更多