How to retrieve a single field(In my case password) using a search criteria(In my case email) in MongoDB(Java)?

StackOverflow https://stackoverflow.com/questions/22762492

Question

Here's what I have tried yet:

    BasicDBObject searchQuery = new BasicDBObject();
    searchQuery.put("email", email_id);        
    DBCursor cursor=collection.find(searchQuery);
    String usr=null;
    String pass=null;
    while(cursor.hasNext())
    {
     usr=(String)cursor.next().get("username");
     pass=(String)cursor.next().get("password");
    }

I'm getting the username value as it is present in the record. But password is returning null.

Was it helpful?

Solution

please try this:

BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("email", email_id);
cursor = collection.find(searchQuery);

DBObject resultElement = null;
resultElement = cursor.next();

if(resultElement.containsField("username")){
     String password = (String) resultElement.get("password");
}

Hope this help :)

OTHER TIPS

I think the best way to do that is using findOne:

DBObject query = new BasicDBObject("email", email_id);
user = collection.findOne(query);
if (user != null) 
{
  usr=  user.get("username").toString();
  pass=  user.get("password").toString();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top