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
https://www.mongodb.com/download-center#community
image1

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
C:\data\db>mongod
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
image2
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
image3
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 :- http://mongodb.github.io/mongo-java-driver/?_ga=1.55182892.626961242.1477037916
mongodb-driver-core-3.0.1.jar:-https://oss.sonatype.org/content/repositories/releases/org/mongodb/mongodb-driver-core/3.3.0/
bson-3.3.0.jar :- https://oss.sonatype.org/content/repositories/releases/org/mongodb/bson/3.3.0/
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[] ) {

try{

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

List dbs = mongoClient.getDatabaseNames();
for(String dbase : dbs){
System.out.println(dbase);
}

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

No comments: