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
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.
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.
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)
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.
_id
is an ObjectId
, you should use this:
String id = doc.getObjectId("_id").toHexString();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With