MongoDB Java Insert Document In Collection - Java @ Desk

Friday, June 13, 2014

MongoDB Java Insert Document In Collection

MongoDB Java Insert Document In Collection

There are three different ways to insert a document in a collection using Java Driver :
1) com.mongodb.BasicDBObject - Create the new object and keep on appending the fields into the object

2) com.mongodb.BasicDBObjectBuilder - Static method "start()" returns the new instance of the class. Add fields into the object and "get()" method of the class returns the DBObject object that can be inserted into a collection.

3) java.util.Map - Create a Map object and put the values in key, value fashion. Add them into a collection

Java Example :

import java.util.HashMap;
import java.util.Map;

import com.mongodb.BasicDBObject;
import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;

public class MongoDBInsertJava {
 public static void main(String args[]) throws UnknownHostException {
  DB database = getDatabase();

  DBCollection collection = database.getCollection("loans");

  BasicDBObject personalLoanDBObject = new BasicDBObject();
  personalLoanDBObject.append("name", "Personal Loan");
  personalLoanDBObject.append("interest", 10.0);

  BasicDBObject homeLoanDBObject = new BasicDBObject();
  homeLoanDBObject.append("name", " Home Loan");
  homeLoanDBObject.append("interest", 12.0);

  BasicDBObjectBuilder documentBuilderDetail = BasicDBObjectBuilder.start();
  documentBuilderDetail.add("name", "Personal Loan");
  documentBuilderDetail.add("interest", 10.0);
  Map<String, Object> map = new HashMap<String, Object>();
  map.put("name", "Personal Loan");
  map.put("interest", 10.0);

  collection.insert(new BasicDBObject(map));

 public static DB getDatabase() throws UnknownHostException {
  Mongo mongo = new Mongo("localhost", 27017);
  DB database = mongo.getDB("yourdb");
  return database;

No comments:

Post a Comment