Java & MongoDB - 如何获取 MongoDB 文档中 _id 的值?

Kol*_*yon 5 java database server-side mongodb

我正在使用此处指定的 API:http://api.mongodb.com/java/current/org/bson/Document.html

这是我的代码:

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

我已经检查过它doc已返回Document,但我无法访问 的值_id

错误是这样说的:

java.lang.ClassCastException: org.bson.types.ObjectId cannot be cast to java.lang.String
Run Code Online (Sandbox Code Playgroud)

小智 1

您是否尝试过以下操作:

doc.get("_id");
Run Code Online (Sandbox Code Playgroud)