Header Ads Widget

Responsive Advertisement

Create MongoDb Connection Java Code


Connecting to MongoDB in Java involves using the MongoDB Java Driver. Here’s a step-by-step guide to setting up a MongoDB connection in Java:

Step 1: Add MongoDB Java Driver Dependency

If you are using Maven, add the MongoDB Java Driver dependency to your pom.xml:

xml

<dependency>

    <groupId>org.mongodb</groupId>

    <artifactId>mongodb-driver-sync</artifactId>

    <version>4.7.1</version>

</dependency>

 

Step 2: Create a MongoDB Connection

  1. Import Necessary Classes:

java

import com.mongodb.client.MongoClients;

import com.mongodb.client.MongoClient;

import com.mongodb.client.MongoDatabase;

import com.mongodb.client.MongoCollection;

import org.bson.Document;

 

  1. Establish a Connection to MongoDB:

java

public class MongoDBConnectionExample {

    public static void main(String[] args) {

        // Connection string to MongoDB server

        String connectionString = "mongodb://localhost:27017";

       

        // Create a new MongoClient

        try (MongoClient mongoClient = MongoClients.create(connectionString)) {

            // Connect to the database

            MongoDatabase database = mongoClient.getDatabase("mydatabase");

 

            // Print the database name

            System.out.println("Connected to database: " + database.getName());

 

            // Get a collection (create it if it does not exist)

            MongoCollection<Document> collection = database.getCollection("mycollection");

 

            // Create a sample document

            Document doc = new Document("name", "John Doe")

                                .append("age", 29)

                                .append("city", "New York");

 

            // Insert the document into the collection

            collection.insertOne(doc);

 

            // Retrieve the document from the collection

            Document retrievedDoc = collection.find().first();

            System.out.println("Retrieved document: " + retrievedDoc.toJson());

        }

    }

}

 

 

Explanation

  1. Connection String:
    • String connectionString = "mongodb://localhost:27017"; specifies the MongoDB server's address and port. Adjust it to match your MongoDB server configuration.
  2. Create a MongoClient:
    • MongoClient mongoClient = MongoClients.create(connectionString); establishes the connection.
  3. Get Database and Collection:
    • MongoDatabase database = mongoClient.getDatabase("mydatabase"); gets the mydatabase database.
    • MongoCollection<Document> collection = database.getCollection("mycollection"); gets or creates the mycollection collection.
  4. Create and Insert Document:
    • Document doc = new Document("name", "John Doe").append("age", 29).append("city", "New York"); creates a sample document.
    • collection.insertOne(doc); inserts the document into the collection.
  5. Retrieve Document:
    • Document retrievedDoc = collection.find().first(); retrieves the first document from the collection.
    • System.out.println("Retrieved document: " + retrievedDoc.toJson()); prints the retrieved document.

Some other implementation for deeper understand:

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.io.UnsupportedEncodingException;

import java.net.URLEncoder;

import java.util.List;

import java.util.concurrent.TimeUnit;

 

import net.sf.json.JSONArray;

import net.sf.json.JSONObject;

 

import org.bson.BsonDateTime;

import org.bson.BsonDocument;

import org.bson.Document;

 

import cltool4j.BaseCommandlineTool;

import cltool4j.args4j.Option;

 

import com.google.gson.GsonBuilder;

import com.mongodb.BasicDBObject;

import com.mongodb.DBObject;

import com.mongodb.MongoClient;

import com.mongodb.MongoClientURI;

import com.mongodb.client.MongoCollection;

import com.mongodb.client.MongoCursor;

import com.mongodb.client.MongoDatabase;

import com.mongodb.client.model.CreateCollectionOptions;

import com.mongodb.client.model.IndexOptions;

import com.mongodb.client.model.UpdateOptions;

 

public class MongoDBInstaller extends BaseCommandlineTool {

 

 @Option(name = "-componentName", required = true, metaVar = "componentName", usage = "Component name(kamical/Mongoservice/Pricefeed)")

 private String componentName;

 

 @Option(name = "-keyStorePasswd", required = false, metaVar = "keyStorePassword", usage = "Key Store Password")

 private String keyStorePasswd;

 

 @Option(name = "-user", required = true, metaVar = "user", usage = "Mongo db username")

 private String user;

 

 @Option(name = "-pwd", required = true, metaVar = "password", usage = "Mongo db password")

 private String password;

 

 @Option(name = "-db", required = true, metaVar = "db", usage = "Mongo db name")

 private String db;

 

 @Option(name = "-host", required = true, metaVar = "host", usage = "Mongo db host or replica set primary node details")

 private String host;

 

 @Option(name = "-port", required = true, metaVar = "port", usage = "Mongo db port or replica set primary node port")

 private int port;

 

 @Option(name = "-auth", required = false, metaVar = "auth", usage = "Mongo db authMechanism Example:SCRAM-SHA-256,SCRAM-SHA-1,PLAIN,GSSAPI,MONGO-X509")

 private String auth;

 

 @Option(name = "-replicaSetName", required = false, metaVar = "replicaSetName", usage = "Replica Set name if you are working on replica set mongo db")

 private String replicaSetName;

 

 @Option(name = "-connectTimeoutMS", required = false, metaVar = "connectTimeoutMS", usage = "connection time in MiliSecond of mongo db")

 private int connectTimeoutMS;

 

 private Encryptor encryptor;

 

//https://examples.javacodegeeks.com/software-development/mongodb/java-mongodb-authentication-example/

 

 @Override

 protected void run() throws Exception {

  //Find out user id and password are encrypted or not

  boolean userflag=Encryptor.isEncryptedValue(user);

  if(userflag){

   //if it encrypted then do the decrypt of user name

   user = Encryptor.decrypt(Encryptor.getInnerEncryptedValue(user));

  }

  boolean passflag=Encryptor.isEncryptedValue(password);

  if(passflag){

   //if it encrypted then do the decrypt of password

   password = Encryptor.decrypt(Encryptor.getInnerEncryptedValue(password));

  }

  /* Imp. Note -

         *      1.  Developers will need to encode the 'auth_user' or the 'auth_pwd' string if it contains the <code>:</code> or

         *      the <code>@</code> symbol. If not, the code will throw the <code>java.lang.IllegalArgumentException</code>.

         *      2.  If the 'auth_user' or the 'auth_pwd' string does not contain the <code>:</code> or the

         *      <code>@</code> symbol, we can skip the encoding step.

         */

 

  try {

   user = URLEncoder.encode(user, "UTF-8");

   password = URLEncoder.encode(password, "UTF-8");

  } catch (UnsupportedEncodingException ex) {

   ex.printStackTrace();

  }

  String clientUrl = null;

  clientUrl = "mongodb://" + user + ":" + password + "@" + host + ":"+ port +"/"

    + db+"?";

  if (auth != null) {

   clientUrl=clientUrl+ "authMechanism=" + auth+"&";

  }

  if (replicaSetName != null) {

   clientUrl=clientUrl+ "replicaSet=" + replicaSetName+"&";

  }

  if (connectTimeoutMS >0) {

   clientUrl=clientUrl+ "connectTimeoutMS=" + connectTimeoutMS+"&";

  }else{

   clientUrl=clientUrl+ "connectTimeoutMS=300000";

  }

  // Mongodb connection string.

  MongoClientURI uri = new MongoClientURI(clientUrl);

  // Connecting to the mongodb server using the given client uri.

  MongoClient mongoClient = new MongoClient(uri);

 

  MongoDatabase mongoDB = null;

 

  //Initialize Encryptor

  encryptor = new ConfigEncryptor(keyStorePasswd);

 

  InputStream in = this.getClass().getResourceAsStream("/component/"+componentName+"/collections.js");

  BufferedReader reader = new BufferedReader(new InputStreamReader(in));

  GsonBuilder gsonBuilder = new GsonBuilder();

  gsonBuilder.disableHtmlEscaping();

  gsonBuilder.setPrettyPrinting();

  Collections content = gsonBuilder.create().fromJson(reader,

    Collections.class);

  List<Collection> collections = content.getCollections();

  for (Collection collection : collections) {

   String dbName = db;

   if(dbName == null || dbName.length() <= 0) {

    dbName = collection.getSchema();

   }

   mongoDB = mongoClient.getDatabase(dbName);

  

   System.out.println(String.format("Processing collection:%s schema :%s", collection.getName(),dbName));

 

   MongoCollection<Document> dbCollection =  null;

 

   if(collectionExists(collection.getName(),mongoDB)){

    dbCollection = mongoDB.getCollection(collection.getName());

   } else{

    if(collection.isCapped()){

     CreateCollectionOptions createCollectionOptions = new CreateCollectionOptions();

     createCollectionOptions.capped(true);

     if(collection.getMaxDocument()!=0)

      createCollectionOptions.maxDocuments(collection.getMaxDocument());

     if(collection.getMaxSize()!=0)

      createCollectionOptions.sizeInBytes(collection.getMaxSize());

     mongoDB.createCollection(collection.getName(),createCollectionOptions);

    }else {

     mongoDB.createCollection(collection.getName());

    }

    dbCollection = mongoDB.getCollection(collection.getName());

   }

  

   Index[] indexes = collection.getIndexes();

   if (indexes != null && indexes.length > 0) {

    for (Index index : indexes) {

     BasicDBObject keys = new BasicDBObject();

     IndexColumn[] indexColumns = index.getKeys();

     for (IndexColumn indexColumn : indexColumns) {

      keys.append(indexColumn.getColumn(),

        indexColumn.isAscending() ? 1 : -1);

      System.out.println("Index --> "+indexColumn.getColumn()+" is unique "+index.isUnique());

     }

     IndexOptions indexOptions = new IndexOptions();

     indexOptions.sparse(index.isSparse());

     indexOptions.background(true);

     indexOptions.unique(index.isUnique());

 

     if(index.getName()!=null) {

      indexOptions.name(index.getName());

     }

 

     System.out.println("Index unique "+index.isUnique()+" --> meta data --> "+indexOptions.toString());

     System.out.println("Index keys "+keys);

     if(index.isSparse() || index.isUnique()){

      dbCollection.createIndex(keys, indexOptions);

     } else {

      System.out.println("ensuring index ... "+dbCollection.toString());

      IndexOptions options = new IndexOptions();

      options.background(true);

      if(index.getName()!=null) {

       options.name(index.getName());

      }

      if(index.getExpiryInSeconds() > 0) {

       options.expireAfter(index.getExpiryInSeconds(), TimeUnit.SECONDS);

      }

      dbCollection.createIndex(keys, options);

     }

    }

   }

   if (collection.isMetaData()) {

    String[] uniqueCols = collection.getUnique();

    JSONArray data = getCollectionData(collection.getName());

    if (data != null && data.size() > 0) {

     System.out.println("\t Metadata table: Trying to insert/update the data");

     for (Object obj : data.toArray()) {

      JSONObject record = (JSONObject) obj;

      DBObject object = new BasicDBObject(record);

      BsonDocument bsonDocument1 = BsonDocument.parse(record.toString());

      BsonDocument bsonDocument = new BsonDocument("$set",bsonDocument1);

     

      //To populate created and last_updated on insertion

      if(collection.isPopulateCreatedDate()){

       BsonDocument insertDate = new BsonDocument("created", new BsonDateTime(System.currentTimeMillis())).append("last_updated", new BsonDateTime(System.currentTimeMillis()));

       bsonDocument.append("$setOnInsert", insertDate);

      }

     

      BasicDBObject basicDBObject = new BasicDBObject();

      for (String col : uniqueCols) {

       basicDBObject.append(col, object.get(col));

      }

      if(collection.isPartial()){

       long count = dbCollection.countDocuments(basicDBObject);//count(basicDBObject);

       if(count == 0){

        UpdateOptions updateOptions = new UpdateOptions();

        updateOptions.upsert(true);

        dbCollection.updateOne(basicDBObject, bsonDocument, updateOptions);

        System.out.println(String.format("\tAdded/updated record %s", obj));

       } else {

        if(collection.getName().equals("user")){

         object = updateRecord(record);

         bsonDocument = new BsonDocument("$set",BsonDocument.parse(object.toString()));

         UpdateOptions updateOptions = new UpdateOptions();

         updateOptions.upsert(true);

         dbCollection.updateOne(basicDBObject, new BsonDocument("$set",bsonDocument),updateOptions);

         System.out.println(String.format("\tEntry already found, Updated it. %s", obj));

        } else if(collection.getName().equals("exchange_quote_feed") || collection.getName().equals("data_import_feed")){ //Price feed component changes

         dbCollection.updateOne(basicDBObject, bsonDocument);

         System.out.println(String.format("\tEntry already found, Updated it. %s", obj));

        } else {

         System.out.println(String.format("\tEntry already found, so skipping it. %s", obj));

        }

       }

      } else {

 

       if(collection.isInsertOnlyOnce()){

        long count = dbCollection.countDocuments();//count();

        if(count== 0){

         UpdateOptions updateOptions = new UpdateOptions();

         updateOptions.upsert(true);

         dbCollection.updateOne(basicDBObject, bsonDocument,updateOptions);

        }

       }

       else {

        if (collection.isInsertNewData()) {

         long count = dbCollection.countDocuments(basicDBObject);//count(basicDBObject);

         if (count == 0) {

          UpdateOptions updateOptions = new UpdateOptions();

          updateOptions.upsert(true);

          dbCollection.updateOne(basicDBObject, bsonDocument,updateOptions);

          System.out.println(String.format("\tAdded/updated record %s", obj));

         }

        } else {

         UpdateOptions updateOptions = new UpdateOptions();

         updateOptions.upsert(true);

         dbCollection.updateOne(basicDBObject, bsonDocument,updateOptions);

         System.out.println(String.format("\tAdded/updated record %s", obj));

        }

       }

      }

     }

    }

   }

  }

  mongoClient.close();

 }

 

 private DBObject updateUserRecord(JSONObject userId){

  JSONObject user = userId.getJSONObject("User");

  JSONObject finapp = userId.getJSONObject("finincalapp");

  JSONObject fastLink = userId.getJSONObject("fastdatalink");

  JSONObject adminCredentials = userId.getJSONObject("kartik");

  BasicDBObject update = new BasicDBObject()

   .append("userId.loginName", encryptor.encrypt(user.getString("loginName")))

   .append("userId.password", encryptor.encrypt(user.getString("password")))

   .append("fastlink.consumerKey", encryptor.encrypt(fastLink.getString("consumerKey")))

   .append("fastlink.consumerSecret", encryptor.encrypt(fastLink.getString("consumerSecret")))

   .append("finapp.consumerKey", encryptor.encrypt(finapp.getString("consumerKey")))

   .append("finapp.consumerSecret", encryptor.encrypt(finapp.getString("consumerSecret")))

   .append("admin.consumerKey", encryptor.encrypt(adminCredentials.getString("consumerKey")))

   .append("admin.consumerSecret", encryptor.encrypt(adminCredentials.getString("consumerSecret")))

   .append("admin.accessToken", encryptor.encrypt(adminCredentials.getString("accessToken")))

   .append("admin.accessTokenSecret", encryptor.encrypt(adminCredentials.getString("accessTokenSecret")));

  return new BasicDBObject("$set",update).append("$unset", new BasicDBObject("adminUser",""));

 }

 

 private JSONArray getCollectionData(String collectionName) {

  InputStream in = this.getClass().getResourceAsStream("/component/"+componentName+

    "/data/" + collectionName + ".js");

  StringBuilder sb = new StringBuilder();

  if (in != null) {

   BufferedReader br = new BufferedReader(new InputStreamReader(in));

   try {

    String line = br.readLine();

 

    while (line != null) {

     sb.append(line);

     line = br.readLine();

    }

   } catch (IOException e) {

 

   } finally {

    try {

     br.close();

    } catch (IOException e) {

    }

   }

  }

  JSONArray json = null;

  if (sb.length() > 0) {

   json = JSONArray.fromObject(sb.toString());

   if(collectionName.equals("config")){

    for(Object object:json){

     JSONObject config = (JSONObject)object;

     boolean hasEncryptedKey = config.containsKey("encrypted");

     if(hasEncryptedKey){

      boolean encrypted = config.getBoolean("encrypted");

      if(encrypted){

       String value = config.getString("value");

       config.put("value", encryptor.encrypt(value));

      }

     }

    }

   }

  }

  return json;

 }

 

 public boolean collectionExists(final String collectionName, MongoDatabase mongoDatabase) {

  MongoCursor<String> collectionNames = mongoDatabase.listCollectionNames().iterator();

  while (collectionNames.hasNext()) {

   if (collectionNames.next().equalsIgnoreCase(collectionName)) {

    return true;

   }

  }

  return false;

 }

 

 public void updateUserCollection(){

 }

 

 public void updateConfigCollection(){

 }

 public static void main(String[] args) {

  run(args);

 }

}

 

Conclusion

This example demonstrates how to connect to MongoDB, create a database and collection, insert a document, and retrieve it using the MongoDB Java Driver. This setup provides a basic foundation for interacting with MongoDB from Java applications

 





Post a Comment

0 Comments