fgonzalez
fgonzalez

Reputation: 3877

Converting DBObject to a POJO using MongoDB Java

I'm a starting to use MongoDb and developping a small web application that connect to this Mongo Database. I have a DAO with a method to find a user from the db according to the email address assigned to the user. Each user should have a unique email address so I can assume I'll get only one document. How can then convert the DBObject to a User entity?

Here my code:

@Override
public User findUserByEmailAddress(String email) {
    DB db=MongoHelper.getDb();


    BasicDBObject query = new BasicDBObject(); 
    query.put("email", email);
    DBCollection users=db.getCollection("users");
    DBCursor cursor = users.find(query);

    DBObject user=cursor.next();

  //Code to convert the DBObject to a User and return the User
}

Thank you very much in advance!

Upvotes: 1

Views: 3253

Answers (1)

Alex P
Alex P

Reputation: 1751

DBObject is a map, so you can get required values by simply accessing it by corresponding key.

For example:

DBObject query = QueryBuilder.start("email").is(email).get();
DBCursor cursor = users.find(query);

while (cursor.hasNext()) {

   DBObject user = cursor.next();
   String firstName = (String)user.get("first_name");
   String lastName = (String)user.get("last_name");

   //TODO: use extracted properties to build User object   
}

Note that depending on document structure, the returned property can be itself a map. So appropriate casting is required. In addition, I would not assume there can be only one email per user in the document database (due to errors, wrong input etc). It should be enforced on the application level.

Upvotes: 1

Related Questions