Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusion about mongodb java driver [duplicate]

I am a beginner to MongoDB and I'm playing around with it using the JAVA driver.

I have the following code

MongoClient client = new MongoClient();
DB d = client.getDB("world");
DBCollection c = d.getCollection("zips");
DBCursor cursor = c.find();

Now my question is that I want to use a simple cursor to go through the documents. The getDB() method is deprecated but it works fine. In the documentation it's mentioned that getDB can be replaced with MongoClient.getDatabase(); but getDatabase() returns a MongoDatabase not a DB.

Can someone point out the correct way to make a DBCursor without using any deprecated method. Thanks.

PS: I know there are frameworks like morphia, jongo etc but please keep them out of this discussion. I want to currently resort only to the JAVA driver. EDIT: The difference is about getting a cursor in the JAVA driver not between DB and MongoClient

like image 496
Newton Avatar asked May 02 '16 11:05

Newton


People also ask

Is Java compatible with MongoDB?

To interact with MongoDB from our Java application, we will use a piece of software called the Java Driver, which is an official and recommended MongoDB driver application for the Java language.

Is MongoDB thread safe Java?

"Thread Safe" however for Java is fine as it's designed to grab from the single pool in different operations among threads. In brief, if the official documentation says it's okay, then it probably is as someone has tested it.

What is MongoDB driver legacy?

“The MongoDB Legacy driver mongodb-driver-legacy is the legacy synchronous Java driver whose entry point is com. mongodb. MongoClient and central classes include com. mongodb. DB , com.


1 Answers

Yes. Thats true. you can replace getDB with getDatabase. this is how you can use it.

        /**** Get database ****/
        // if database doesn't exists, MongoDB will create it for you
        MongoDatabase mydatabase = mongoClient.getDatabase("mydatabase");

        /**** Get collection / table from 'testdb' ****/
        // if collection doesn't exists, MongoDB will create it for you

        FindIterable<Document> mydatabaserecords = mydatabase.getCollection("collectionName").find();
        MongoCursor<Document> iterator = mydatabaserecords.iterator();
        while (iterator.hasNext()) {
            Document doc = iterator.next();
            // do something with document
        }

Example:

So lets say that your document is something like below:

{
  "name": "Newton",
  "age": 25
}

Then fields can be fetched as below

while (iterator.hasNext()) {
    Document doc = iterator.next();
    String name = doc.getString("name");
    int age = doc.getInteger("age");
    System.out.println("Name: " + name);
    System.out.println("Age: " + age);
}

I hope this clears your doubt.

like image 169
Deendayal Garg Avatar answered Oct 12 '22 11:10

Deendayal Garg