Suggested Pages

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

pom.xml

...
<dependency>
      <groupId>org.mongodb</groupId>
      <artifactId>mongo-java-driver</artifactId>
      <version>3.0.2</version>
</dependency>


MongoDBConnection.java

...

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();
  updateOptions.upsert(true);
  long count = mongoCollection.count(new Document(identity, document.get(identity)));
  if (count == 0) {
   mongoCollection.insertOne(document);
  } else {
   mongoCollection.replaceOne(new Document(identity, document.get(identity)), document, updateOptions);
  }
 }

         public void close() {
  mongo.close();
 }

 
}

No comments :

Post a Comment

Suggested Pages