代码之家  ›  专栏  ›  技术社区  ›  Kellen Stuart Alan

Java和MongoDB-如何在MongoDB文档中获取\u id的值?

  •  5
  • Kellen Stuart Alan  · 技术社区  · 7 年前

    我正在使用此处指定的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
    

    我已经查过了 doc 已返回 Document 但我无法访问 _id .

    错误显示如下:

    java.lang.ClassCastException: org.bson.types.ObjectId cannot be cast to java.lang.String
    
    3 回复  |  直到 7 年前
        1
  •  1
  •   d3t0x    7 年前

    _id 是一个 ObjectId ,则应使用此选项:

    String id = doc.getObjectId("_id").toHexString(); 
    
        2
  •  1
  •   Mạnh Quyết Nguyễn    7 年前

    您是否尝试了以下操作:

    doc.get("_id");
    
        3
  •  1
  •   Kellen Stuart Alan    7 年前

    我不得不跑:

    doc.get("_id").toString();
    

    获取文本ID。