tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 No SQL > Mongo DB > How to Save or Update Document

How to Save or Update Document 

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 save or update a document in Mongo database.

File Name  :  
Author  :  Sudhakar KV
Email  :  [email protected]
package com.bethecoder.tutorials.mongodb.tests;


import com.mongodb.BasicDBObject;
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 SaveOrUpdateCollectionTest {

   @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("students");
      //List collection before update
      System.out.println("--- Before Update ---");
      System.out.println("--- After First Update ---");

      //Update the old document with new document
      DBObject query = new BasicDBObject().append("name""Sudhakar");
      DBObject newDocument = new BasicDBObject();
      //This method creates a new document if it doesn't exist
      collection.update(query, newDocument, true, false);
      System.out.println("--- After Second Update ---");
      newDocument = new BasicDBObject();
      //This method creates a new document if it doesn't exist
      collection.update(query, newDocument, true, false);
    catch (UnknownHostException e) {
    catch (MongoException e) {
  private static void listAll(DBCollection collection) {
    //Queries for all objects in this collection
    DBCursor dbCursor = collection.find();
    DBObject record = null;
    while (dbCursor.hasNext()) {
      record =;

It gives the following output,
--- Before Update ---
--- After First Update ---
{ "_id" : { "$oid" : "503cbff70354230a4a972b80"} , "name" : "Sudhakar" , "mobile" : "987654321"}
--- After Second Update ---
{ "_id" : { "$oid" : "503cbff70354230a4a972b80"} , "name" : "Sudhakar" , "mobile" : "100000001"}



Books Recommendation

bl  br