Java MongoDB Connectivity -code snippet for Insert,Update,Search,Delete operations

Insert

Save a document (data) into a collection (table) named “user”.
 DBCollection table = db.getCollection("user");
 BasicDBObject document = new BasicDBObject();
 document.put("name", "mkyong");
 document.put("age", 30);
 document.put("createdDate", new Date());
 table.insert(document);
 
 
 Update 
Update a document where “name=mkyong”.
 DBCollection table = db.getCollection("user");
 
 BasicDBObject query = new BasicDBObject();
 query.put("name", "mkyong");

 BasicDBObject newDocument = new BasicDBObject();
 newDocument.put("name", "mkyong-updated");
    
 BasicDBObject updateObj = new BasicDBObject();
 updateObj.put("$set", newDocument);

 table.update(query, updateObj);
Search
Find document where “name=mkyong”, and display it with DBCursor
 DBCollection table = db.getCollection("user");

 BasicDBObject searchQuery = new BasicDBObject();
 searchQuery.put("name", "mkyong");

 DBCursor cursor = table.find(searchQuery);

 while (cursor.hasNext()) {
  System.out.println(cursor.next());
 }

 Delete example

Find document where “name=mkyong”, and delete it.
 DBCollection table = db.getCollection("user");

 BasicDBObject searchQuery = new BasicDBObject();
 searchQuery.put("name", "mkyong");

 table.remove(searchQuery);

Popular posts from this blog

DDL DML DCL and TCL

Implementation of Calculator using lex and yacc

A Register Allocation algorithm that translates the given code into one with a fixed number of registers.