Friday, 15 May 2015

Textual description of firstImageUrl

MongoDB 3 With Java

Here is the simple java program to insert data in MongoDB database. version 3.0 API is changed a bit . MongoClient.getDB method is deprecated and MongoClient.getDatabase() is used , which returns an instance of MongoDatabse type .

package mongoDBExample;

import java.util.Arrays;
import java.util.List;

import org.bson.Document;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

public class MongoDBTest
{
 public static void main(String[] args)
 {
  MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017"));
  
  MongoDatabase database = mongoClient.getDatabase("Test");
  List books = Arrays.asList(1251,2512);
  Document person = new Document("_id", "ABHSIHEK")
                              .append("name", "java roots")
                              .append("address", new BasicDBObject("street", "sad java")
                                                           .append("city", "mongos")
                                                           .append("state", "mongod")
                                                           .append("zip", 5151))
                              .append("books", books);
  
  MongoCollection collection= database.getCollection("people");
     collection.insertOne(person);
  mongoClient.close();
  /**
   * Older code which is deprecated in 3.0
   */
  /*
  DB db = mongoClient.getDB("Test");
  List books = Arrays.asList(27464, 747854);
  DBObject obj = new BasicDBObject("_id", "javaroots").append("name", "java roots")
                .append("address", new BasicDBObject("street", "awesome java")
                .append("city", "mongos")
                .append("state", "mongod")
                .append("zip", 5151))
.append("books", books);;
  
  DBCollection col = db.getCollection("people");
  col.insert(obj);*/
        
  
 }
}


Also we dont need to use getLastError method , because now exception is thrown if any error occurs .


Post Comments And Suggestions !!