使用java检索mongodb数组元素

时间:2017-06-16 03:14:19

标签: java mongodb jsp

我在我的数据库中有这个。

{
"_id" : ObjectId("59424f41baaacf1f40815ae8"),
"first_name" : "Yazid",
"last_name" : "Amir",
"gender" : "Male",
"hobby" : ["Memanah", "Business", "Fusal", "Makan"]
}

假设我要检索" Business"来自数组的爱好。所以我的代码就像这样

MongoCollection collection = db.getCollection("customers");
BasicDBObject whereQuery = new BasicDBObject();
whereQuery.put("first_name", "Yazid");

MongoCursor<Document> cursor = collection.find(whereQuery).iterator();

try {
while (cursor.hasNext()) {
    Document str = cursor.next();



    out.println(str.get("hobby.0")); // display specific field
}
} finally {
cursor.close();
}

但是,结果为null。

1 个答案:

答案 0 :(得分:3)

使用List<Document>存储数组

while (cursor.hasNext()) {
    Document str = cursor.next();

    List<Document> list = (List<Document>)str.get("hobby");

    out.println(list.get(0)); // display specific field
}