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.
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");
collection.drop();
//List collection before update
System.out.println("--- Before Update ---");
listAll(collection);
System.out.println("--- After First Update ---");
//Update the old document with new document
DBObject query = new BasicDBObject().append("name", "Sudhakar");
DBObject newDocument = new BasicDBObject();
newDocument.put("name", "Sudhakar");
newDocument.put("mobile", "987654321");
//This method creates a new document if it doesn't exist
collection.update(query, newDocument, true, false);
listAll(collection);
System.out.println("--- After Second Update ---");
newDocument = new BasicDBObject();
newDocument.put("name", "Sudhakar");
newDocument.put("mobile", "100000001");
//This method creates a new document if it doesn't exist
collection.update(query, newDocument, true, false);
listAll(collection);
private static void listAll(DBCollection collection) {
//Queries for all objects in this collection
DBCursor dbCursor = collection.find();
DBObject record = null;
while (dbCursor.hasNext()) {
record = dbCursor.next();
System.out.println(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"}