问题描述
我正在尝试从具有匹配的"EmployeeName"的最后更新("timeSliceStart")行中获取_id
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"); }
Mongo DB中的数据::
Data in Mongo DB::
{ "_id" : { "employeeId" : "1234567890", "@objectName" : "FeedMetadata" }, "school" : false, "college" : null, "errorCount" : 0, "errors" : [], "EmployeeName" : "Peter"}
{ "_id" : { "employeeId" : "1234567890", "@objectName" : "FeedMetadata" }, "school" : false, "college" : null, "errorCount" : 0, "errors" : [], "EmployeeName" : "Peter"}
正在打印的结果是:{ "employeeId" : "1234567890" , "@objectName" : "FeedMetadata"}
The result that is getting printed is :{ "employeeId" : "1234567890" , "@objectName" : "FeedMetadata"}
我只想要_id中的employeeId,我尝试了_id.employeeId ;
,但是它返回了null
.有没有办法只显示employeeId?
I want just the employeeId from _id, I tried _id.employeeId ;
, but it returned null
.Is there a way to display only the 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循环:
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);
}
这篇关于我正在尝试查询mongodb集合以获取一个特定的id字段-的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!