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

前端 未结 5 1216
你的背包
你的背包 2020-12-01 07:30

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

{
  \"_id\" : ObjectId(\"4f693d40e4b04cde19f17205\"),
  \"         


        
5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-01 08:01

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

提交回复
热议问题