mongodb java get array code example

Example: mongodb java read array

MongoClient client = new MongoClient("localhost", 27017);
MongoDatabase database = client.getDatabase("employee_db");
MongoCollection<Document> collection = database
				.getCollection("employees");

List<Document> employees = (List<Document>) collection.find().into(
  new ArrayList<Document>());

for (Document employee : employees) {

  // courses is a List in a DB
  List<Document> courses = (List<Document>) employee.get("courses");
  for (Document course : courses) {
    System.out.println("name = " + employee.getString("name")
                       + " course details below");
    System.out.println("course name = " + course.getString("name"));
    System.out.println("cours type = " + course.getString("type"));
  }

}

Tags:

Java Example