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

ぐ巨炮叔叔 提交于 2019-11-27 20:25:22
Chris

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

For those who are seeking a more up to date method, especially with 3.4:

import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import org.bson.types.ObjectId;

import static com.mongodb.client.model.Filters.eq;

//......
MongoCollection<Document> myCollection = database.getCollection("myCollection");
Document document = myCollection.find(eq("_id", new ObjectId("4f693d40e4b04cde19f17205"))).first();
if (document == null) {
    //Document does not exist
} else {
    //We found the document
}
Nifras Nipy

You can do this

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

Solved it by using query as-

query.putAll((BSONObject)query);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!