Converting DBObject to Java Object while retrieve values from MongoDB

后端 未结 2 597
终归单人心
终归单人心 2021-02-15 13:52

From my Java application, I have stored the values in mongoDB in ArrayList(set of Java objects). How can I retrieve the data from DBObject

I am storing the data in mong

2条回答
  •  长情又很酷
    2021-02-15 14:16

    You can do it as follows :

    List students = new ArrayList();
    
    BasicDBObject query = new BasicDBObject();
    query.put("user", username); 
    DBCursor cursor = theCollection.find(query); 
    while (cursor.hasNext()) {
        DBObject theObj = cursor.next();
        //How to get the DBObject value to ArrayList of Java Object?
    
        BasicDBList studentsList = (BasicDBList) theObj.get("students");
        for (int i = 0; i < studentsList.size(); i++) {
            BasicDBObject studentObj = (BasicDBObject) studentsList.get(i);
            String firstName = studentObj.getString("firstName");
            String lastName = studentObj.getString("lastName");
            String age = studentObj.getString("age");
            String gender = studentObj.getString("gender");
    
            Student student = new Student();
            student.setFirstName(firstName);
            student.setLastName(lastName);
            student.setAge(age);
            student.setGender(gender);
    
            students.add(student);
        }               
    }
    

提交回复
热议问题