Java MongoDB : Insert a document

In this tutorial, we show you 4 ways to insert below JSON data into a “document“, via Java MongoDB API.

Test Data

Test data in JSON format.

{
	"database" : "mkyongDB",
	"table" : "hosting",
	"detail" : 
		{
			records : 99,
			index : "vps_index1",
			active : "true"
		}
	}
}

1. BasicDBObject example

	BasicDBObject document = new BasicDBObject();
	document.put("database", "mkyongDB");
	document.put("table", "hosting");
 
	BasicDBObject documentDetail = new BasicDBObject();
	documentDetail.put("records", 99);
	documentDetail.put("index", "vps_index1");
	documentDetail.put("active", "true");
 
	document.put("detail", documentDetail);
 
	collection.insert(document);

2. BasicDBObjectBuilder example

	BasicDBObjectBuilder documentBuilder = BasicDBObjectBuilder.start()
		.add("database", "mkyongDB")
		.add("table", "hosting");
 
	BasicDBObjectBuilder documentBuilderDetail = BasicDBObjectBuilder.start()
	.add("records", 99)
	.add("index", "vps_index1")
	.add("active", "true");
 
	documentBuilder.add("detail", documentBuilderDetail.get());
 
	collection.insert(documentBuilder.get());

3. Map example

	Map<String, Object> documentMap = new HashMap<String, Object>();
	documentMap.put("database", "mkyongDB");
	documentMap.put("table", "hosting");
 
	Map<String, Object> documentMapDetail = new HashMap<String, Object>();
	documentMapDetail.put("records", 99);
	documentMapDetail.put("index", "vps_index1");
	documentMapDetail.put("active", "true");
 
	documentMap.put("detail", documentMapDetail);
 
	collection.insert(new BasicDBObject(documentMap));

4. JSON parse example

	String json = "{'database' : 'mkyongDB','table' : 'hosting'," +
	  "'detail' : {'records' : 99, 'index' : 'vps_index1', 'active' : 'true'}}}";
 
	DBObject dbObject = (DBObject)JSON.parse(json);
 
	collection.insert(dbObject);

Full example

package com.mkyong.core;
 
import java.net.UnknownHostException;
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.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.util.JSON;
 
/**
 * Java MongoDB : Insert a Document
 * 
 */
public class InsertDocumentApp {
  public static void main(String[] args) {
 
    try {
 
	Mongo mongo = new Mongo("localhost", 27017);
	DB db = mongo.getDB("yourdb");
 
	DBCollection collection = db.getCollection("dummyColl");
 
	// 1. BasicDBObject example
	System.out.println("BasicDBObject example...");
	BasicDBObject document = new BasicDBObject();
	document.put("database", "mkyongDB");
	document.put("table", "hosting");
 
	BasicDBObject documentDetail = new BasicDBObject();
	documentDetail.put("records", 99);
	documentDetail.put("index", "vps_index1");
	documentDetail.put("active", "true");
	document.put("detail", documentDetail);
 
	collection.insert(document);
 
	DBCursor cursorDoc = collection.find();
	while (cursorDoc.hasNext()) {
		System.out.println(cursorDoc.next());
	}
 
	collection.remove(new BasicDBObject());
 
	// 2. BasicDBObjectBuilder example
	System.out.println("BasicDBObjectBuilder example...");
	BasicDBObjectBuilder documentBuilder = BasicDBObjectBuilder.start()
		.add("database", "mkyongDB")
                .add("table", "hosting");
 
	BasicDBObjectBuilder documentBuilderDetail = BasicDBObjectBuilder.start()
                .add("records", "99")
                .add("index", "vps_index1")
		.add("active", "true");
 
	documentBuilder.add("detail", documentBuilderDetail.get());
 
	collection.insert(documentBuilder.get());
 
	DBCursor cursorDocBuilder = collection.find();
	while (cursorDocBuilder.hasNext()) {
		System.out.println(cursorDocBuilder.next());
	}
 
	collection.remove(new BasicDBObject());
 
	// 3. Map example
	System.out.println("Map example...");
	Map<String, Object> documentMap = new HashMap<String, Object>();
	documentMap.put("database", "mkyongDB");
	documentMap.put("table", "hosting");
 
	Map<String, Object> documentMapDetail = new HashMap<String, Object>();
	documentMapDetail.put("records", "99");
	documentMapDetail.put("index", "vps_index1");
	documentMapDetail.put("active", "true");
 
	documentMap.put("detail", documentMapDetail);
 
	collection.insert(new BasicDBObject(documentMap));
 
	DBCursor cursorDocMap = collection.find();
	while (cursorDocMap.hasNext()) {
		System.out.println(cursorDocMap.next());
	}
 
	collection.remove(new BasicDBObject());
 
	// 4. JSON parse example
	System.out.println("JSON parse example...");
 
	String json = "{'database' : 'mkyongDB','table' : 'hosting'," +
	  "'detail' : {'records' : 99, 'index' : 'vps_index1', 'active' : 'true'}}}";
 
	DBObject dbObject = (DBObject)JSON.parse(json);
 
	collection.insert(dbObject);
 
	DBCursor cursorDocJSON = collection.find();
	while (cursorDocJSON.hasNext()) {
		System.out.println(cursorDocJSON.next());
	}
 
	collection.remove(new BasicDBObject());
 
    } catch (UnknownHostException e) {
	e.printStackTrace();
    } catch (MongoException e) {
	e.printStackTrace();
    }
 
  }
}

Output…

BasicDBObject example...
{ "_id" : { "$oid" : "4dc9ef6f237f86642d5b34bd"} , "database" : "mkyongDB" , 
"table" : "hosting" , "detail" : { "records" : "99" , "index" : "vps_index1" , "active" : "true"}}
 
BasicDBObjectBuilder example...
{ "_id" : { "$oid" : "4dc9ef6f237f86642d5b34be"} , "database" : "mkyongDB" , 
"table" : "hosting" , "detail" : { "records" : "99" , "index" : "vps_index1" , "active" : "true"}}
 
Map example...
{ "_id" : { "$oid" : "4dc9ef6f237f86642d5b34bf"} , "detail" : { "index" : "vps_index1" , 
"active" : "true" , "records" : "99"} , "table" : "hosting" , "database" : "mkyongDB"}
 
JSON parse example...
{ "_id" : { "$oid" : "4dc9ef6f237f86642d5b34c0"} , "database" : "mkyongDB" , 
"table" : "hosting" , "detail" : { "records" : 199 , "index" : "vps_index1" , "active" : "true"}}
What is “_id” ?
The _id is added by MongoDB automatically, for identity purpose. From MongoDB document, it said, all element names that start with “_”, “/” and “$” are reserved for internal use.

References

  1. BasicDBObject Java Doc
  2. BasicDBObjectBuilder Java Doc
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

  • Pingback: stop parking()

  • Pingback: water ionizers()

  • Pingback: alkaline water benefits()

  • Pingback: laan nu og her()

  • Pingback: car parking()

  • Pingback: fue.mobi()

  • Pingback: call tvpackages.net today()

  • Pingback: get satellite tv()

  • Pingback: tvpackages.net()

  • Pingback: kangen water()

  • Pingback: kangen()

  • Pingback: alkaline water()

  • Pingback: watch movies online()

  • Pingback: stream movies()

  • Pingback: watch free movies online()

  • Pingback: Blue Coaster33()

  • Alex Anderson

    I am in love with mongo now.
    Thanks sir :)

  • Pingback: Java + MongoDB hello world example()

  • Pingback: MongoDB – A NoSQL Database : SL Tech Umbrella()

  • armen

    Bravo!!!!

  • Pingback: Java MongoDB Tutorial()

  • amine

    i want insert in mongodb via http but doesn’t work :'(
    plz help

    public class addProduct extends Activity{
    	TextView codbarText,typeText,produitText,avisText,descriptionText,dateText;
    	String codbarText_,typeText_,produitText_,avisText_,descriptionText_,dateText_;
    	public void onCreate(Bundle savedInstanceState) {
    	    super.onCreate(savedInstanceState);
    	    setContentView(R.layout.addproduct);
     
             codbarText=(TextView) findViewById(R.id.editText1);
             typeText=(TextView) findViewById(R.id.editText2);
             produitText=(TextView) findViewById(R.id.editText3);
             avisText=(TextView) findViewById(R.id.editText4);
             descriptionText=(TextView) findViewById(R.id.editText5);
             dateText=(TextView) findViewById(R.id.editText6);
            Button btEnreg = (Button) this.findViewById(R.id.buttonenregistrer);
            btEnreg.setOnClickListener(btEnregListener);
            Intent thisIntent =getIntent();
            String contents=thisIntent.getExtras().getString(&quot;contents&quot;);
            codbarText.setText(contents);
     
    	}
    	private Button.OnClickListener btEnregListener = new Button.OnClickListener() {
    	    public void onClick(View v) {
    	    	codbarText_ = codbarText.getText().toString();
    	    	typeText_ = typeText.getText().toString();
    	    	produitText_ = produitText.getText().toString();
    	    	avisText_ = avisText.getText().toString();
    	    	descriptionText_ = descriptionText.getText().toString();
    	    	dateText_ = dateText.getText().toString();
    			insert_product(codbarText_, typeText_, produitText_, avisText_, descriptionText_,dateText_);
    			Toast.makeText(addProduct.this, &quot;Produit crée avec succès&quot;, Toast.LENGTH_SHORT).show();
    			finish();
               }
    	};
    	public void insert_product(String codbar, String type, String produit, String avis, String description,String date){
    		try {
    	        HttpClient client = new DefaultHttpClient();  
    	        HttpPost post = new HttpPost(new Uri.Builder()
    		    .scheme(&quot;https&quot;)
    		    .authority(&quot;mongolab.com&quot;)
    		    .path(&quot;api/1/databases/***/collections/****&quot;)
    		    .appendQueryParameter(&quot;apiKey&quot;,&quot;4e9c48f0e4b016e146bf33b0&quot;).build().toString()); 
    	        StringEntity se = new StringEntity(&quot;{\&quot;codbar\&quot;:\&quot;&quot;+codbar+&quot;\&quot;,&quot; +
    	        &quot;\&quot;type\&quot;:\&quot;&quot;+type+&quot;\&quot;,\&quot;produit\&quot;:\&quot;&quot;+produit+&quot;\&quot;,\&quot;avis\&quot;:\&quot;&quot;+avis+&quot;\&quot;,&quot; +
    	        &quot;\&quot;description\&quot;:\&quot;&quot;+description+&quot;\&quot;,\&quot;date\&quot;:\&quot;&quot;+date+&quot;\&quot;}&quot;);
    	        post.setEntity(se);
    	        client.execute(post);  
     
    	    } catch (Exception e) {
    	    	Log.e(&quot;gson&quot;, e.getMessage(), e);
    	        e.printStackTrace();
    	    }
    	}
    	public String readJsonFeed(String URL) throws URISyntaxException {
    		StringBuilder builder = new StringBuilder();
    		HttpClient client = new DefaultHttpClient();
     
    		Log.i(&quot;gson&quot;, &quot;readJsonFeed&quot;);
     
    		HttpGet httpGet = new HttpGet(URL);
     
    		Log.i(&quot;gson&quot;, &quot;httpGet uri : &quot; + httpGet.getURI().toString());
     
    		try {
    			HttpResponse response = client.execute(httpGet);
    			StatusLine statusLine = response.getStatusLine();
    			int statusCode = statusLine.getStatusCode();
     
    			Log.i(&quot;gson&quot;, &quot;statusCode : &quot; + statusCode);
     
    			if (statusCode == 200) {
    				HttpEntity entity = response.getEntity();
    				InputStream content = entity.getContent();
    				BufferedReader reader = new BufferedReader(
    						new InputStreamReader(content));
    				String line;
    				while ((line = reader.readLine()) != null) {
    					builder.append(line);
    					Log.i(&quot;aaaaaaaaaaaaaaaaaaaaaaaaaa&quot;,line);
     
    				}
    			} else {
    				Log.e(&quot;gson&quot;, &quot;Failed to download file&quot;);
    			}
    		} catch (ClientProtocolException e) {
    			Log.e(&quot;gson&quot;, e.getMessage(), e);
    			//e.printStackTrace();
    		} catch (IOException e) {
    			Log.e(&quot;gson&quot;, e.getMessage(), e);
    			//e.printStackTrace();
    		}
    		return builder.toString();
    	}
    }