How to query documents using "_id" field in Java mongodb driver?

user837208 picture user837208 · Mar 21, 2012 · Viewed 73.2k times · Source

I am trying to find documents in MongoDB by searching on "_id" key. My document looks like this-

{
  "_id" : ObjectId("4f693d40e4b04cde19f17205"),
  "hostname" : "hostnameGoesHere",
  "OSType" : "OSTypeGoesHere"
}

I am trying to search this document as-

ObjectId id= new ObjectId("4f693d40e4b04cde19f17205");        
BasicDBObject obj = new BasicDBObject();        
obj.append("_id", id);        
BasicDBObject query = new BasicDBObject();        
query.putAll(query);

But I get below error-

error: reference to putAll is ambiguous, both method putAll(Map) in BasicBSONObject and method putAll(BSONObject) in BasicBSONObject match
        query.putAll(query);

The append method of BasicDBObject supports (String Key, Value) and if I pass "_id" as String to this method, no documents are matched.

So my question is how do I pass "_id"?

Answer

Chris picture Chris · Oct 8, 2012

Not sure if others might be searching for answers on this topic, but here is the easiest way to search for a MongoDB record based on "_id". The MongoDB documentation is not updated and still shows ObjectId as being part of the com.mongodb package (it also generally does not give a lot of information on searching by ObjectId).

import org.bson.types.ObjectId;

public DBObject findDocumentById(String id) {

    BasicDBObject query = new BasicDBObject();
    query.put("_id", new ObjectId(id));

    DBObject dbObj = collection.findOne(query);
    return dbObj;
}