Confusion about java mongodb driver

I am new to MongoDB and I play 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 documents. The getDB () method is deprecated, but it works great. The documentation mentioned that getDB can be replaced with MongoClient.getDatabase (); but getDatabase () returns MongoDatabase, not the database.

Can anyone point out the correct way to create a DBCursor without using the deprecated method. Thanks.

PS: I know that there are such frameworks as morphine, jongo, etc., but please do not allow their discussion. Currently, I want to use only the JAVA driver. EDIT: the difference is getting the cursor in the JAVA driver not between DB and MongoClient

+5
source share
1 answer

Yes. It's true. you can replace getDB with getDatabase. so 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, let's say your document looks something like this:

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

Then the fields can be selected 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); } 

Hope this clears your doubts.

+8
source

All Articles