2017-06-16 95 views
0

我在我的数据库中有这个。使用java检索mongodb数组元素

{ 
"_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(); 
} 

但是,结果为空。

+0

获取这实际上是'“业余爱好”'属性,然后访问像一个正常的Java列表的数组。 MongoDB“Dot notation”不适用于Java对象。 –

回答

1

使用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 
} 
+0

哇。谢谢。有用!! –

+0

很高兴我能帮忙:) –