tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 
 No SQL > Mongo DB > How to insert Nested Documents using BasicDBObjectBuilder

How to insert Nested Documents using BasicDBObjectBuilder 

MongoDB is a scalable, high-performance, open source NoSQL database. It offers Ad hoc queries, Indexing, Replication, Load balancing, File storage (GridFS), Aggregation, MapReduce and Server-side JavaScript execution. This requires the library mongo-2.8.0.jar to be present in the classpath. The following example shows how to insert a nested document in Mongo database.

File Name  :  
com/bethecoder/tutorials/mongodb/tests/NestedDocInsertionTest2.java 
Author  :  Sudhakar KV
Email  :  kvenkatasudhakar@gmail.com
   
package com.bethecoder.tutorials.mongodb.tests;

import java.net.UnknownHostException;

import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

public class NestedDocInsertionTest2 {

  /**
   @param args
   */
  public static void main(String[] args) {
    try {
      //Connect to mongoDB with given IP and PORT
      Mongo mongo = new Mongo("localhost"27017);
      
      //Get the database object
      DB database = mongo.getDB("mytestdb");
      
      //Gets a collection with a given name.
        //If the collection does not exist, a new collection is created.
      DBCollection collection = database.getCollection("studentdetails");
      
      //Create and insert document to collection
      BasicDBObjectBuilder docBuilder = BasicDBObjectBuilder.start();
      docBuilder.add("name""Sriram");
      docBuilder.add("age"2);
      
      DBObject address = BasicDBObjectBuilder.start()
        .append("DoorNo""1-2-3-4")
        .append("City""Bangalore")
        .get();
      
      docBuilder.add("address", address);
      
      //Saves a document to the database
      collection.insert(docBuilder.get());
      
      //Queries for all objects in this collection
      DBCursor dbCursor = collection.find();
      DBObject record = null;
      
      while (dbCursor.hasNext()) {
        record = dbCursor.next();
        System.out.println(record);
      }
      
    catch (UnknownHostException e) {
      e.printStackTrace();
    catch (MongoException e) {
      e.printStackTrace();
    }
  }

}
   

It gives the following output,
{ "_id" : { "$oid" : "503cc7c742e21985cdd17df8"} , 
	"name" : "Sriram" , "age" : 2 , 
	"address" : { "DoorNo" : "1-2-3-4" , "City" : "Bangalore"}}


                    Print

   



Books Recommendation

 
 
bl  br