Java -- MongoDB collection.find() by _id -


i trying element collection using unique _id, can not find how.

this code

mongoclient mongoclient = new mongoclient("localhost", 27017); mongodatabase database = mongoclient.getdatabase("db"); mongocollection<document> collection =   database.getcollection("coll"); 

if query db

basicdbobject query=new basicdbobject("info.i0","0"); document mydoc = collection.find(query).first(); system.out.println(mydoc.tojson()); 

i output

{ "_id" : { "$oid" : "560ea3f205240f065a3e9d19" }, "name" : "mongodb", "type" : "database", "count" : 1, "info" : { "i0" : "0", "i1" : "1", "i2" : "2", "i3" : "3", "i4" : "4", "i5" : "5", "i6" : "6", "i7" : "7", "i8" : "8", "i9" : "9" } } 

but if try

basicdbobject query=new basicdbobject("_id.$oid","560ea3f205240f065a3e9d19"); document mydoc = collection.find(query).first(); system.out.println(mydoc.tojson()); 

i null pointer exception, mydoc null.

what doing wrong?

$oid there preserve bson representation.

it has meaning mongodb internal json parsers.

you have use _id in query:

basicdbobject query=new basicdbobject("_id",new objectid("560ea3f205240f065a3e9d19"));

also, note _id field of type objectid , not string.

you have wrap in objectid constructor.


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -