java mongodb connection

The following two tabs change content below.
Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Latest posts by Prasad Kharkar (see all)

Till now we’ve seen CRUD operations in mongodb, but a java developer will not write mongodb commands. He/She needs to access mongodb from java code. A java mongodb connection is required for it and it can be done using java mongodb driver

Java Mongodb Connection

We need to have java mongodb driver jar in our project. mongodb driver jar also has dependencies on bson and mongodb-driver-core jars. Download below jars.

Create Eclipse Project:

Open your favorite workspace and create any java project. Add these 3 jars in project’s build path. For people using eclipse,

Right click on project  > Properties > Java Build Path > Add External Jars

After you are done adding all these 3 jars for java mongodb connection, you shoudl be able to see project structure such as below.

dependencies added

 

Start mongodb server

You can see how to start mongodb server on windows

Code for Java Mongodb connection

Let us understand what we’ve done for java mongodb connection.

  • import com.mongodb.MongoClient accepts information about mongodb server to connect to.
  • client.getConnectPoint() returns the connection point.
  • localhost means we are trying to connect to mongodb running on same machine
  • 27017 is the default port number on which mongodb runs

We’ve written java mongodb connection program, let us see the output after running it. Press ctrl+F11 in eclipse and you’ll see the output below

localhost:27017

This means java mongodb connection is successful and now you will be able to access databases and query over collections. From next article, we will see further operations those can be done using java mongodb connection.

Share Button

Prasad Kharkar

Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

2 thoughts on “java mongodb connection

Leave a Reply

Your email address will not be published. Required fields are marked *