8

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 mongoDB like this:

{  "students" : [{"firstName" : "Jesse", "lastName" : "Varnell", "age" : "15", "gender" : "M" }, { "firstName" : "John", "lastName" : "Doe", "age" : "13", "gender" : "F"}] }

I am having the Java Object for the Student like:

public class Student {
    public String firstName;
    public String lastName;
    public String age;
    public String gender;  // M, F      
}

I am retrieving the data from mongoDB like:

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?
}
Parvin Gasimzade
  • 25,180
  • 8
  • 56
  • 83
It's me
  • 1,065
  • 6
  • 15
  • 30

2 Answers2

14

You can do it as follows :

List<Student> students = new ArrayList<Student>();

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);
    }               
}
Parvin Gasimzade
  • 25,180
  • 8
  • 56
  • 83
  • Thanks Parvin for the response. When I tried the above code, I got the following exception: Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to com.mongodb.BasicDBList Where the theObj.get("students") is in String. – It's me Jan 03 '14 at 11:56
  • Are you sure that students field in DB stores data as array? If the json object you write above is correct then this code should work. I try same code on my local and it works correctly. Most probably you students in DB as string not array. – Parvin Gasimzade Jan 03 '14 at 12:02
  • Yes. I just copied the values from DB only. Actually, It is storing the data as Array only. It is not a string. – It's me Jan 03 '14 at 12:07
  • Can you share the full json object for single document? – Parvin Gasimzade Jan 03 '14 at 12:10
  • This is the single document from MongoDB: { "loginid" : "john.doe@mail.com", "streetAddress" : "4 King Farm Rd", "zipcode" : "17532", "residenceType" : "single", "cityState" : "Holtwood, PA", "phone" : "7172845772", "comments" : "", "students" : [{ "firstName" : "Ronn", "lastName" : "Perkins", "age" : "50", "gender" : "M" }, { "firstName" : "Lavinia", "lastName" : "Perkins", "age" : "47", "gender" : "F" }], "_created" : NumberLong("1339102359831"), "_modified" : NumberLong("1351954577018") } – It's me Jan 03 '14 at 12:35
  • I tried the same code with the given data on my local and it works.Check your code again. – Parvin Gasimzade Jan 03 '14 at 12:41
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/44418/discussion-between-parvin-and-vijay) – Parvin Gasimzade Jan 03 '14 at 13:10
5

You generally use an ORM tool for that (though it wouldn't be meaningful to call it ORM in the case of a non relational database).

There are several such tools. I like spring-data, which hides a lot of boiler plate code for you and gives you a simple, clean syntax. Something like this:

@Repository
public class UserRepositoryImpl implements UserRepository {

    private MongoTemplate mongoTemplate;

    @Autowired
    public UserRepositoryImpl(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }

    @Override
    public User findsUserByUsernameAndPassword(String userName, String encodedPassword) {
        return mongoTemplate.findOne(query(where("userName").is(userName).and("encodedPassword").is(encodedPassword)), User.class);
    }
}

With the User class defined as:

@Document(collection = "users")
public class User {

    private String userName;

    private String encodedPassword;

    // snip getters and setters

}
Mzzl
  • 3,926
  • 28
  • 39
  • 2
    Unrelated but I'm from the future (2022), we called these ODM (Object Document Mapping) – Seraf Oct 31 '22 at 13:26