1

I'm just switching from MySQL to MongoDB and it's a little confusing. We have our database stored in MongoDB and using Java-Selenium in the front end. I am trying to retrieve just one single data from the database. The code below retrieves all the data present in the database:

DBCursor cursor = dbCollection.find();

while(cursor.hasNext())
{
    int i=1;
    System.out.println(cursor.next());
    i++;
}

This is my database lets say:

{
    "name" : "Su_123", 
    "email" : "test@gmail.com", 
    "_id" : ObjectId("12345656565656")
}

I want to retrieve just the email field (test@gmail.com) from the document where _id = ObjectId("12345656565656") and store this in a String field.

How do I go about coding this? find() retrieves the entire row.

halfer
  • 19,824
  • 17
  • 99
  • 186
Su123
  • 11
  • 2
  • Have you looked at the manual? The driver I use allows the use of `find(filter, format)`, where `filter` is what you want to match on, and `format` is the fields you want in the result(s). [See here](https://docs.mongodb.com/manual/reference/method/db.collection.find/). – halfer Jan 15 '20 at 18:39

1 Answers1

0

For newer drivers, since 3.7.1


To get specific document that matches a filter:

Document doc = collection.find(eq("email", "test@gmail.com")).first();

It can be used to find the first document where the field email has the value test@gmail.com. And pass an eq filter object to specify the equality condition.

By the same logic using id:

Document document = myCollection.find(eq("_id", new ObjectId("12345656565656"))).first();

To get specific value of the field from selected document:

String value = (String) doc.get("email");

For older drivers like 2.14.2 and 2.13.3

To get a single document with a query:

BasicDBObject query = new BasicDBObject("email", "test@gmail.com");

cursor = coll.find(query);

try {
   while(cursor.hasNext()) {
       //System.out.println(cursor.next());
   }
} finally {
   cursor.close();
}

To see more details for newer Mongodb Java driver.
To see more details for older Mongodb Java driver.
To see more details from Mongodb Official Docs.

invzbl3
  • 5,872
  • 9
  • 36
  • 76