Thursday, October 27, 2016

MongoDB CRUD Operation using JAVA

1:- Insert Data inside MongoDb:
package com.test.siddhu;
import java.util.Date;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
public class MongoDBConnectionClass {

public static void main( String args[] ) {

try{

MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
DB db = mongoClient.getDB("siddhudb");
DBCollection table = db.getCollection("user");
BasicDBObject document = new BasicDBObject();
document.put("name", "Siddharatha Dhumale");
document.put("age", 37);
document.put("createdDate", new Date());
table.insert(document);

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

2:- Update Data inside MongoDb
package com.test.siddhu;
import java.util.Date;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
public class MongoDBConnectionClass {
public static void main( String args[] ) {
try{
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
DB db = mongoClient.getDB("siddhudb");
DBCollection table = db.getCollection("user");
BasicDBObject query = new BasicDBObject();
query.put("name", "Siddharatha Dhumale");
BasicDBObject newDocument = new BasicDBObject();
newDocument.put("name", "Siddharatha Dhumale changed");
BasicDBObject updateObj = new BasicDBObject();
updateObj.put("$set", newDocument);
table.update(query, updateObj);
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}
image6
3:- Delete Data inside Mongodb
package com.test.siddhu;
import java.util.Date;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
public class MongoDBConnectionClass {
public static void main( String args[] ) {
try{
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
DB db = mongoClient.getDB("siddhudb");

DBCollection table = db.getCollection("user");
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("name", "Siddharatha Dhumale changed");
table.remove(searchQuery);
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}

image7
Note :- Same can also be done using MongDb shell
https://docs.mongodb.com/getting-started/shell/

No comments: