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 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");
//List collection before update
listAll(collection);
//Update the old document with new document
DBObject query = new BasicDBObject().append("name", "Sudhakar");
DBObject newDocument = new BasicDBObject();
newDocument.put("name", "Venkata Sudhakar");
newDocument.put("mobile", "987654321");
//This method updates only the first document matching criteria
collection.update(query, newDocument);
System.out.println();
System.out.println();
//List collection after update
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);
}
}
}