MongoDb : Java Driver

Last update on April 14 2018 06:14:57 (UTC/GMT +8 hours)

Introduction

MongoDB provides connectivity for Java client applications using Java driver. Using the Java driver is simple, just include the driver jar mongo.jar in your classpath. You will get more information about the Java API from here.

Authentication (Optional) :
MongoDB can be run in a secure mode where access to databases is controlled via authentication. When run in this mode, any client application must provide a list of credentials which will be used to authenticate against. In the Java driver, you simply provide the credentials when creating a MongoClient instance:

Find a document

To show or find a document is simple, use findOne() operation to get the first document in the collection. This method returns a single document, and it's useful for things where there only is one document, or you are only interested in the first.

Using a Cursor to retrieve all documents

To get all the documents in the collection, we have used the find() method. The find() method returns a DBCursor object which allows us to iterate over the set of documents that matched our query. So to query all of the documents and print them out :

A single document Query

We can create a query to pass to the find() method to get a subset of the documents in our collection. For example, if we wanted to find the document for which the value of the "rollno" field is 2, we would do the following ;