Java - MongoDB collection.find () by _id

I am trying to get an item from a collection using its unique _id, but I cannot find it.

This is my code.

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

If I request my db with

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

I get a conclusion

{ "_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 because myDoc is null.

What am I doing wrong?

+4
source share
3 answers

$oidthere is only save the BSON representation .

It only makes sense for MongoDB internal JSON parsers.

You need to use _idin your request:

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

Also note that the field _idis of type ObjectId, not String.

ObjectId.

+6

, , . $?

:

_id ; , , . ($). (.). .

http://docs.mongodb.org/manual/core/document/

0

JSON (scala): Json.obj("_id" -> Json.obj("$oid" -> "560ea3f205240f065a3e9d19"))

0

Source: https://habr.com/ru/post/1610041/


All Articles