Java querying the objectid example in mongodb

  • 2020-04-01 03:13:24
  • OfStack

After looking for a long time, the method of querying the objectid is all wrong. Mongovue can query it, but I don't know how to query it in Java

1. Inquiry method in mongovue:


{"_id" : ObjectId("5326bfc0e6f780b21635248f")}

2. Query method in pure mongodb:


db.collect.find({ "_id" : ObjectId("5326bfc0e6f780b21635248f") })

3. Query method in Java:


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


Related articles: