java - 使用java检索mongodb数组元素

标签 java mongodb jsp

我的数据库中有这个。

{
"_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/

相关文章:

java - 如何从Android Room中的多个数据库中进行选择(How to attach databases)

java - 反转二维数组的行

java - 如何使用 Java 将 BsonDocument 对象写入文件并再次读取

MongoDB 标签键索引

node.js - 如何使用 Mongoose 创建遵循模型的嵌入式文档?

java - CrudRepository 的 findAll() 方法返回空值

java - 如何在jsp中查找默认网关ip地址

javascript - 单击浏览器的后退按钮后,Opera 浏览器不会在页面上触发 JS 或服务器端代码 (JSP)

java - Struts2 - 在 JSP 迭代期间调用 Javascript 函数

java - 如何在jar内部xml配置更改和应用程序重启后进行SL​​F4J+Logback刷新设置?