我试图使用" _id"从mongodb中检索记录。领域。但是我输出的是null。
我的代码:
MongoClient mongo = new MongoClient("localhost",27017);
DB db = mongo.getDB("sample");
DBCollection col = db.getCollection("matching");
BasicDBObject query = new BasicDBObject();
query.put("_id", new ObjectId("56cec592fe3fc16f6b564761"));
DBObject dbObj = col.findOne(query);
System.out.println(dbObj); //getting output as null
我在mongodb的记录:
{
"_id" : ObjectId("56cec592fe3fc16f6b564761"),
"name" : "vishal",
"location" : "Delhi",
"Profession" : "SE",
"number" : 2
}
答案 0 :(得分:0)
试试这个
DBObject dbObj = col.findOne(new ObjectId("56cec592fe3fc16f6b564761"));
答案 1 :(得分:0)
您可以导入org.bson.types.ObjectId
,然后将id
打包并在查询中将其用作
import org.bson.types.ObjectId;
...
MongoClient mongo = new MongoClient("localhost",27017);
DB db = mongo.getDB("sample");
DBCollection col = db.getCollection("matching");
BasicDBObject query = new BasicDBObject();
query.put("_id", new ObjectId("56cec592fe3fc16f6b564761"));
DBObject dbObj = col.findOne(query);