我正在尝试查询 mongodb 集合以获取一个特定的 id 字段 -

I am trying to querymongodb collection to get one particular id field -

我正在尝试从具有匹配 "EmployeeName"

的最后更新 ("timeSliceStart") 行中获取 _id
DBCursor cursor = collection.find(EmployeeName).sort(new BasicDBObject("timeSliceStart", -1)).limit(1);
 while(cursor.hasNext()) {
            String result = cursor.next().get("id"); }

Mongo 数据库中的数据::

{ "_id" : { "employeeId" : "1234567890", "@objectName" : "FeedMetadata" }, "school" : false, "college" : null, "errorCount" : 0, "errors" : [], "EmployeeName" : "Peter" }

打印的结果是: { "employeeId" : "1234567890" , "@objectName" : "FeedMetadata"}

我只想要 _id 中的 employeeId,我尝试了 _id.employeeId ;,但它返回了 null。 有没有办法只显示employeeId?

我的 Java 程序 -

  BasicDBObject whereQuery = new BasicDBObject();
    whereQuery.put("EmployeeName", empName);
    DBCursor cursor = collection.find(whereQuery).sort(new BasicDBObject("lastUpdate", -1)).limit(1);
    while(cursor.hasNext()) {
        String result = cursor.next().get("_id").toString();
        System.out.println(result);
    }

您可以像这样更改 while 循环:

while(cursor.hasNext()) {
    String result = ((HashMap)((BasicDBObject)(cursor.next().get("_id")))).get("employeeId");
    System.out.println(result);
}