AdrieanKhisbe
AdrieanKhisbe

Reputation: 4058

MongoDB: Cleanly query an object by _id with JavaDriver

I'm trying to update a Mongo objet using is _id. However i don't find the proper syntax to make it work using JavaDriver, here is what I last try.

BasicDBObject filtre = new BasicDBObject ("_id", new BasicDBObject("$oid", id_message));

then giving to the coll.update method. I manage to make my request work from the shh but didn't manage to trasnlate it properly to Java. (request is something like : db.message.find({"_id" : ObjectId("516a94c4e4b0a315396e4ba3")}); ) ` How do i properly traslate it to Java. (eventually using QueryBuilder)

Upvotes: 0

Views: 135

Answers (1)

WiredPrairie
WiredPrairie

Reputation: 59793

If you're trying to translate:

db.message.find({"_id" : ObjectId("516a94c4e4b0a315396e4ba3")})

to Java, follow this basic pattern:

MongoClient mongoClient = new MongoClient();
DB db = mongoClient.getDB("testDB");
DBCollection messages= db.getCollection("message");
DBObject query = new BasicDBObject("_id", new ObjectId("516a94c4e4b0a315396e4ba3"));
DBObject messageDoc = messages.findOne(query);

The result would be stored in messageDoc.

The documentation for some reason doesn't cover this basic pattern for some reason currently.

Upvotes: 2

Related Questions