我正在尝试使用java
从mongo中检索一个特定字段("Versions.id"
)
Mongo查询 - db.getCollection('SettlementInstance').find({"_id.timeSlice" : [2018,1,1], "_id.type" : "TRANSMISSION"})
这是存储在mongo集合中的数据。我想使用java
检索"id" : "3d8a3b31-aaa0-4c2e-82b3-5eaaa80d80e1"
{
"_id" : {
"timeSlice" : [
2018,
1,
1
],
"type" : "TRANSMISSION",
"@objectName" : "SettlementInstance"
},
"Versions" : [
{
"id" : "3d8a3b31-aaa0-4c2e-82b3-5eaaa80d80e1",
"status" : "ACTIVE",
"version" : NumberLong(11447)
}
]
}
Java程序我试图检索" id"领域"版本"对象,我的代码给出了异常。
String feedName = "ServicePointInputAdapter";
Mongo mongo = new Mongo(host);
DB db = mongo.getDB(("dbname"));
DBCollection collection = db.getCollection("SettlementInstance");
BasicDBObject whereQuery = new BasicDBObject();
whereQuery.put("_id.type", "TRANSMISSION");
whereQuery.put("_id.timeSlice", Arrays.asList(2018,1,1));
DBCursor cursor = collection.find(whereQuery);
try {
while (cursor.hasNext()) {
DBObject Features = cursor.next();
BasicDBList features = (BasicDBList) Features.get("Versions");
BasicDBObject[] featuresArr = features.toArray(new BasicDBObject[0]);
for (BasicDBObject dbobj : featuresArr) {
***** BasicDBObject si_id = (BasicDBObject) dbobj.get("id"); ***** //Getting error in the line }
}
} finally {
cursor.close();
}
}
}
不幸的是我得到例外的例外 -
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to com.mongodb.BasicDBObject.
有人可以帮我解决问题并检索" Versions.id"来自该系列的领域。
答案 0 :(得分:1)
由于错误清楚地表明您正试图将java.lang.String
投射到com.mongodb.BasicDBObject
投掷java.lang.ClassCastException
如下所示更改代码行(因为BasicDBObject实现了HashMap):
for (BasicDBObject dbobj : featuresArr) {
String id = (String)((HashMap)dbobj).get("id");
System.out.println(id);
}
答案 1 :(得分:0)
此get()方法仅返回值。所以当你这样做时它是一个字符串
dbobj.get("id")
您应该将字段名称作为参数传递,您将获得该值。所以改变这一行如下
BasicDBObject si_id = (BasicDBObject) dbobj.get("id");
to
String dbObjectId = dbobj.get("id");