如何使用_id字段从mongodb获取记录,并使用java在控制台中显示获取的记录

时间:2016-02-25 09:48:59

标签: java mongodb

我试图使用" _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
}

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