0

I have this in my db.

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

Let say that I want to retrieve the "Business" from array hobby. So my code will be like this

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

However, the result is null.

1
  • Get the property which is actually "hobby" and then access the array like a normal Java List. MongoDB "Dot notation" does not apply to Java Objects. Commented Jun 16, 2017 at 3:20

1 Answer 1

3

Use a List<Document> to store your array

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

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

    out.println(list.get(0)); // display specific field
}
Sign up to request clarification or add additional context in comments.

1 Comment

Glad I could help :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.