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

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

Leave a Comment