Thursday, 27 July 2017

Insert a document in Mongodb using java

mongoDB : java : Insert a document


Step 1: Get Mongo client
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );

Step 2: Connect to database
DB db = mongoClient.getDB("sample");

Step 3 : Get collection
DBCollection collection = db.getCollection("employee");
Step 4 : Create a document
BasicDBObject doc = new BasicDBObject("_id", "1").append("firstName", "rajdeo").append("lastName", "singh");

Step 5 : Insert document
collection.insert(doc);


import java.net.UnknownHostException;
import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.DB;
import com.mongodb.DBCollection;

public class InsertDocument {

 /* Step 1 : get mongoCLient */
 public static MongoClient getMongoClient(){
  MongoClient mongoClient = null;
   try {
    mongoClient = new MongoClient( "localhost" , 27017 );
  } catch (UnknownHostException e) {
   e.printStackTrace();
  }
   return mongoClient;
 }
 
 public static void main(String args[]){
  MongoClient mongoClient = getMongoClient();
  
  /* Step 2: Connect to DB */
  DB db = mongoClient.getDB("sample");
  
  /*Step 3 : Get collection */
  DBCollection collection = db.getCollection("employee");
  
  /* Step 4 : Create a document */
  BasicDBObject doc = new BasicDBObject("_id", "1").append("firstName", "rajdeo").append("lastName", "singh");
  
  /* Step 5 : Insert document */
  collection.insert(doc);
  
  System.out.println("Document inserted");
 }
}

No comments:

Post a Comment