import java.net.UnknownHostException;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.Cursor;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;


public class MongoDB {
    private MongoClient mongoClient;
    public static final String SERVER = "localhost";
    public static final int PORT = 27017;

    public MongoDB() throws UnknownHostException {
        mongoClient = new MongoClient(SERVER, PORT);
    }

    public MongoClient getConnection() {
        return mongoClient;
    }

    
	 /*
     * method to create doc in jason.
	 {
	   "title" : "Django", 
	   "year" : "2012", 
	   duration="97", 
	   "kind" : Western
       "natio" : "us"
	   "actor" :{
	              name : "tarantino"
				  age : 54
	             }
	   }
     */
	 public BasicDBObject createDoc(){ 
	    BasicDBObject doc = new BasicDBObject("title", "Django")
           .append("year", "2012")
           .append("duration", 97)
		   .append("natio" : "us"
           .append("actor", new BasicDBObject("name", "tarantino").append("age", 54));
         return doc;
	 }
    
	/*
     * Main for testin the connection.
     */
    public static void main(String[] args) throws UnknownHostException {
	    try {

          MongoDB mongo = new MongoDB();
          DB db = mongo.getConnection().getDB("cinema");
		  
		  
          DBCollection films = db.getCollection("films");
		  
		  films.insert(createDoc());

          DBObject film = films.findOne();
          System.out.println(film);
	      
		  /*
		  In order to get all the documents in the collection, we will use 
		  the find() method. The find() method returns a DBCursor object which
		  allows us to iterate over the set of documents that matched our query
		  */
          DBCursor cursor = films.find();
          while(cursor.hasNext()) {
              DBObject obj = cursor.next();
              System.out.println(obj.toString()); ;
          }
        } finally {
           cursor.close();
        }
    }//end of main
}//end of class
