简体   繁体   中英

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM