MongoDB Java - MongoDB

How to setup MongoDB JDBC driver?

In this chapter, we will explain you how to set up MongoDB JDBC driver.

Installation

Before getting started with using MongoDB in Java programs, you should ensure that you have MongoDB JDBC driver and Java is set up on the machine. Now we will have a look at how to set up MongoDB JDBC driver.

  • First, download the jar from the path Download mongo.jar and ensure to download the latest release of it.
  • Then include the mongo.jar into your classpath.

Connect to Database

For connecting to the database, specify the database name and if the database doesn't exist, then MongoDB will create it automatically.

Below is the code snippet to connect to the database

Now, compile and run the above program for creating a database test. You can always change your path based on your requirement. We are assuming the current version of JDBC driver mongo-2.10.1.jar is available in the current path.

If you are using Windows machine, then you can compile and run the code as follows

Value of auth will be true, if the username and password are valid for the selected database.

Create a Collection

createCollection() method of com.mongodb.DB class can be used to create a collection

Below is the code snippet to create a collection

When program is compiled and executed, it produces below result

Getting/ selecting a collection

To get/select a collection from the database, getCollection() method of com.mongodb.DBCollection class is used.
Code snippets to get/select a collection

When the program is compiled and executed, it produces below result

Insert a document

insert() method of com.mongodb.DBCollection class can be used to insert a document into MongoDB.

Below is the code snippet to insert a document

When the program is compiled and executed, it produces below result

Retrieve All Documents

find() method of com.mongodb.DBCollection class can be used to select all the documents from the collection. This method will return a cursor; therefore you have to iterate this cursor.

Below is the code snippet to select all documents

When the program is compiled and executed, it produces below result

Update Document

For updating a document from the collection, update() method of com.mongodb.DBCollection class is used.

Below is the code snippet to select the first document

When a program is compiled and executed, it produces below result

Delete First Document

For deleting the first document from the collection, first select the documents using findOne() method and then remove method of com.mongodb.DBCollection class.

Below is the code snippet to delete the first document

When the program is compiled and executed, it produces below result

Remaining MongoDB methods save(), limit(), skip(), sort() etc. works same as explained in the subsequent tutorial.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

MongoDB Topics