1

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!

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

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.