Thursday, October 27, 2016

Installation of Mongo DB and accessing it using JAVA

Note: We are using Window O/S hence using msi for installation. Please chose version as per your O/S.
Step 1:- Install Mongo by downloading it from below url

This will create MongoDb Server in your machine at below given position
C:\Program Files\MongoDB\Server\3.2\bin
Step 2: Make entry of C:\Program Files\MongoDB\Server\3.2\bin in System and Env Variable. So that we can access it from cmd prompt.
Step 3:- Create a folder \data\db inside c: folder
i.e. C:\data\db
Step 4:- Run mongod command in side this folder
server will be started with below line
2016-10-27T13:11:17.862+0530 I NETWORK [initandlisten] waiting for connections on port 27017

Step 4:- Run mongo command from another cmd prompt and you will see mongo is able to connect
Step 5:- Create your own Database first using following belwo comman
use siddhudb
Step 6:- to see numbers of db we can use show dbs commands i.e. show dbs. Same way if you want to see current working database just enter db command i.e. db and it will show below output
Step 7:- Your Created database (siddhudb) is not present in list when we type show dbs command. Reason is to display database we need to insert at least one document into it.
db.user.insert({"name":"siddhartha dhumale"})
You will see one data is inserted.
> db.user.insert({"name":"siddhartha dhumale"})
WriteResult({ "nInserted" : 1 })
Now when you enter show dbs command it will show you our created db.
> show dbs
local 0.000GB
siddhudb 0.000GB

Step 8:- Lets try to connect this db using java class. First you need to download required driver for the same. Use below given link. Make sure we had following in our class path
mongodb-driver-3.0.1.jar :-
bson-3.3.0.jar :-
Step 9:- We are using eclipse IDE. Use below given programe to test connection to Mongo using java code. This will display output as name of db we had in our Mongo.
package com.test.siddhu;
import java.util.List;
import com.mongodb.DB;
import com.mongodb.MongoClient;
public class MongoDBConnectionClass {

public static void main( String args[] ) {


// To connect to mongodb server
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );

List dbs = mongoClient.getDatabaseNames();
for(String dbase : dbs){

}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );

No comments: