Java -- MongoDB collection.find() by _id

11,916

$oid is there only to preserve BSON representation.

It only has meaning to MongoDB internal JSON parsers.

You only have to use _id in your query:

BasicDBObject query=new BasicDBObject("_id",new ObjectId("560ea3f205240f065a3e9d19"));

Also, note that the _id field is of type ObjectId and not String.

You will have to wrap it in an ObjectId constructor.

Share:
11,916

Related videos on Youtube

rastabob
Author by

rastabob

Updated on July 09, 2022

Comments

  • rastabob
    rastabob almost 2 years

    I am trying to get an element from a collection by using his unique _id, but I can not find how.

    This is my code

    MongoClient mongoClient = new MongoClient("localhost", 27017);
    MongoDatabase database = mongoClient.getDatabase("DB");
    MongoCollection<Document> collection =   database.getCollection("COLL");
    

    If I query my db with

    BasicDBObject query=new BasicDBObject("info.i0","0");
    Document myDoc = collection.find(query).first();
    System.out.println(myDoc.toJson());
    

    I get as 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 I try

    BasicDBObject query=new BasicDBObject("_id.$oid","560ea3f205240f065a3e9d19");
    Document myDoc = collection.find(query).first();
    System.out.println(myDoc.toJson());
    

    I get a Null pointer exception, as myDoc is null.

    What am I doing wrong?