Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java & MongoDB - How to get the value of _id in a MongoDB document?

Tags:

I'm using the API specified here: http://api.mongodb.com/java/current/org/bson/Document.html

Here's the code I have:

Document doc = collection.find(Filters.eq("field","value")).first();
String id = (String) doc.getString("_id"); // this line throws exception

I already checked that doc has a returned Document but I cannot access the value of _id.

The error says this:

java.lang.ClassCastException: org.bson.types.ObjectId cannot be cast to java.lang.String
like image 575
Kellen Stuart Avatar asked May 22 '18 17:05

Kellen Stuart


People also ask

What Java is used for?

Developers use Java to construct applications in laptops, data centres, game consoles, scientific supercomputers, cell phones, and other devices. Java is the world's third most popular programming language, after Python and C – according to the TIOBE index, which evaluates programming language popularity.

What exactly is Java?

Java is a programming language and computing platform first released by Sun Microsystems in 1995. It has evolved from humble beginnings to power a large share of today's digital world, by providing the reliable platform upon which many services and applications are built.

Is Java a programming or coding?

Java Introduction Java is a popular programming language, created in 1995. It is owned by Oracle, and more than 3 billion devices run Java. It is used for: Mobile applications (specially Android apps)

What is Java for beginners?

It is a high-level language that is also easy to read and understand. With it, developers can “write once, run anywhere” (WORA), meaning that the compiled Java code will run on all Java-compatible platforms without the need for recompilation.


1 Answers

_id is an ObjectId, you should use this:

String id = doc.getObjectId("_id").toHexString(); 
like image 140
Mạnh Quyết Nguyễn Avatar answered Sep 28 '22 18:09

Mạnh Quyết Nguyễn