Saturday, 10 January 2015

Mongo DB+Java example

In  this tutorial im goiung to expalin how to connect MongoDb with java

1)installing MongoDb on windows
 download mongoDB
Extract it
then go to the comamnd prompt
click enter

then just type

--dbpath is the path where mongodb stores the data we have to create it .if it doesnt exist mongodb will give error

press enter






now mongoDB has been successfully started up


ok now lets connect it with java
1) add mongodb connection jar

rightclickon the project- -->select properties --> click java build path
then add the jar



MongoClient client = new MongoClient();
 connects with mongo db server
now we have created a connection sucessfully with mongoDB. now lets create a database

DB database = client.getDB("soloworld");

// here i have get the database  soloworld .if the database doesnt exist mongo db wil create one for you

create a table aka collection
 DBCollection table = database.getCollection("userprofile");
// if the collection doesnt exist mongodb will create one for you

  BasicDBObject columns = new BasicDBObject();
        columns.put("Name", mongopojo.getName());
        columns.put("Language", mongopojo.getLanguage());
        table.insert(columns);
//here we have inserted record in to the mongo db

below is the full code & output


and the pojo class









No comments:

Post a Comment