I am trying to querymongodb collection to get one

2019-08-18 15:00发布

问题:

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