Pavlo Sidelov
Pavlo Sidelov

Reputation: 11

Get MongoDB document by ID on Java

I have a set of ID's of documents which I add previously in MongoDB.

Then I try to get Document from ID.

String idString = "57f8f50977c8a5b8757f261a";
BasicDBObject whereQuery = new BasicDBObject();
whereQuery.put("_id", idString);
DBCursor cursor = table.find(whereQuery);            
if(cursor.hasNext())
{
 System.out.println("FOUND!" + cursor.next());
}

I get zero results.

But, if I call another field It works and return me document.

BasicDBObject whereQuery = new BasicDBObject();
whereQuery.put("datachain", "AA");
DBCursor cursor = table.find(whereQuery);
if(cursor.hasNext())
{
System.out.println("FOUND!" + cursor.next());
}

FOUND!{ "_id" : { "$oid" : "57f8f50977c8a5b8757f261b"} , "datachain" : "AA" , "createdDate" : { "$date" : "2016-10-08T13:30:49.588Z"}}

What I do wrong? Why I can't find document by ID's? Thnx!

UPD: BasicDBObject whereQuery = new BasicDBObject(); whereQuery.put("_id", new ObjectId("57f8f50977c8a5b8757f261a")); DBCursor cursor = table.find(whereQuery);

Same, no result founded.

Upvotes: 1

Views: 2323

Answers (1)

4J41
4J41

Reputation: 5095

You have to pass the idString as an ObjectId.

whereQuery.put("_id", new ObjectId(idString));

Upvotes: 3

Related Questions