Featured Post

NoSQL use cases

Here are a simple summary of use cases for Cassandra, MongoDB and Redis MongoDB Storing Log Data Speed is the primary perfor...

Thursday, January 19, 2017

Example of Mongo DB Client

An Example of a simple client that uses the java library of MongoDB. Here the library to include in your pom.xml





import java.util.List;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.UpdateOptions;

public class MongoDBConnection {

 private MongoClient mongo;

 private String database;

 public MongoDBConnection(String database, String hostname, int port) {
  this.database = database;
                mongo = new MongoClient(hostname, port);

 public void saveOrUpdate(String json, String identity, String collection) {
  MongoDatabase db = mongo.getDatabase(database);
  MongoCollection mongoCollection = db.getCollection(collection);
  Document document = Document.parse(json);
  UpdateOptions updateOptions = new UpdateOptions();
  long count = mongoCollection.count(new Document(identity, document.get(identity)));
  if (count == 0) {
  } else {
   mongoCollection.replaceOne(new Document(identity, document.get(identity)), document, updateOptions);

         public void close() {


No comments :

Post a Comment