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

笑着哭i 提交于 2019-12-11 14:49:24

问题


I am trying to get _id from last updated("timeSliceStart") row which has matching "EmployeeName"

DBCursor cursor = collection.find(EmployeeName).sort(new BasicDBObject("timeSliceStart", -1)).limit(1);
 while(cursor.hasNext()) {
            String result = cursor.next().get("id"); }

Data in Mongo DB::

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

The result that is getting printed is : { "employeeId" : "1234567890" , "@objectName" : "FeedMetadata"}

I want just the employeeId from _id, I tried _id.employeeId ;, but it returned null. Is there a way to display only the employeeId?

My Java program -

  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);
    }

回答1:


You can change the while loop like this:

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


来源:https://stackoverflow.com/questions/49699907/i-am-trying-to-querymongodb-collection-to-get-one-particular-id-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!