我的数据库中有这个。
{
"_id" : ObjectId("59424f41baaacf1f40815ae8"),
"first_name" : "Yazid",
"last_name" : "Amir",
"gender" : "Male",
"hobby" : ["Memanah", "Business", "Fusal", "Makan"]
}
假设我想从数组爱好中检索“业务”。所以我的代码会是这样的
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();
}
但是,结果为空。
最佳答案
使用 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
}
关于java - 使用java检索mongodb数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44580205/