Mongo DB in Java: Get a single database entry Value by Key

How to get a single value String by using the key of a single return from a Database search query?

As an example, we would get each value in a single row. But we first have to search the collection ( or in SQL terms, a table ) where the email address is equal to some value. In this case we use the [email] variable

See the sample Java code below, Then each line is commented with an explanation

//This will store the single row result in a setter-getter object
Account newAccount = new Account();

//create the "where" query to search an email.
//"email" first parameter is the key. [email] second parameter is //the search string, which is a variable.
BasicDBObject whereQuery = new BasicDBObject();
whereQuery.put("email", email);

//find the collection row, using the where condition created.
DBCursor cursor = accountsColl.find(whereQuery);

//loop the result using a DB cursor
while(cursor.hasNext()) {

 //store the "" value in another object,
 //since directly accessing the result will cause 
 //a NoElementException when this type of loop is used
 DBObject tobj =;

 //Also store the Strings in a separate objects
 String tempName = (String)tobj.get("name");
 String tempEmail = (String)tobj.get("email");
 String tempPass = (String)tobj.get("password");

 //set the results to the Account Object


return newAccount;

One thought on “Mongo DB in Java: Get a single database entry Value by Key

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s