Searching...
Monday, 10 September 2012

Java Mongodb Connection example

20:17

How to create a Java Mongodb Connection

Here is one simple program to connect mongodb from a java class, for the connection we required mong-java-driver. Below are the steps to connect mongodb

1.Create a Maven project and add below dependency in pom.xml

<dependency>
                     <groupId>org.mongodb</groupId>
                     <artifactId>mongo-java-driver</artifactId>
                     <version>2.5.2</version>
              </dependency>

2.Create Mongo object

Mongo mongo = new Mongo("localhost", 27017);

3.Create/get Database

DB db = mongo.getDB("vinudb");

4.Create database collection object

DBCollection collection = db.getCollection("vinuCollection");
Note: if vinuCollection is not existing mongo will create new one

5.Create a document to store values

BasicDBObject document = new BasicDBObject();
document.put("id", 1001);
document.put("name", "My name is Vinu");

6.Save document object

collection.insert(document);


7.Full Example

package com.pretechmongo; 
 import java.net.UnknownHostException; 
import com.mongodb.BasicDBObject; 
import com.mongodb.DB; 
import com.mongodb.DBCollection; 
import com.mongodb.Mongo; 
import com.mongodb.MongoException; 
public class MongoJavaExample { 
       public static void main(String args[]) { 
              try { 
                     Mongo mongo = new Mongo("localhost", 27017);  
                     DB db = mongo.getDB("vinudb"); 
                     DBCollection collection = db.getCollection("vinuCollection");  
                     BasicDBObject document = new BasicDBObject();  
                     document.put("id", 1001);  
                     document.put("name", "My name is Vinu");  
                     collection.insert(document);  
                     System.out.println("Done");  
              } catch (UnknownHostException e) { 
                     // TODO Auto-generated catch block 
                     e.printStackTrace(); 
              } catch (MongoException e) { 
                     // TODO Auto-generated catch block 
                     e.printStackTrace(); 
              } 
       } 
} 




0 comments: