How can I perform Java Connection to MongoDB

MongoDB is one of the most popular NoSQL databases, which can be easily used within the Cloudjiffy. In this guide, shows how to connect this instance with the app and perform some simple operations.

Create Environment

1. Log in to Cloudjiffy account.

2. Create an environment with MongoDB instance (available within the NoSQL section). The preferred application server for the app to be deployed to can be located in the same or separate environment (as an example, we’ve added Tomcat 7):

   

Click Create and wait a couple of minutes for my environment to appear at the dashboard.

MongoDB Configurations

1. Check the email inbox - it should contain a message from Robot@Cloudjiffy with the database details:

                         

2. Click the Open in browser button for the MongoDB node within my dashboard or use the Access URL from the email to access the database admin panel.

                                        

Log in using the abovementioned credentials.

3. Create a new database by switching to the Databases tab and typing a Name for it (e.g. MongoDB-connect) within the Create Database form.

     

Click Save to continue.

4. Next, I need to create a user for this DB - thus, navigate to the Execute tab and choose my newly created database via the corresponding drop-down list.

    

Then type the following command within the input frame above:

db.createUser({ user: "user_name", pwd: "password", roles:[{ role: "readWrite", db: "db_name"}]})

where

  • user_name - the desired name of my new DB user
  • password - password for this user
  • db_name - the name of the database the newly created user will get the read/write permissions for

After that, click the Execute button and wait for the success response.

5. Now, return to the dashboard and create a separate file for storing database-connection information.

Note that I can specify all the required for connection data directly in my code (application). In the given example we put these settings to the file, which is read by our test application (presented within the next guide section).

Click the Config button next to application server in the corresponding environment (Tomcat 7 in our case).

  

In the opened tab, create a new mydb.cfg file inside the home directory and specify the following strings there:

         host={db_access_url} 
         dbname={db_name}
         user={user_name}

         password={password}

  

where

  • {db_access_url} - link to the database admin panel (find it within the corresponding email or click Open in the browser next to the MongoDB node and copy it from the address bar) without https://part
  • {db_name} - name of the created database (MongoDB-connect in our case)
  • {user_name} - the name of the DB user I’ve assigned to this database (dbuser in our case)
  • {password} - the corresponding user’s password

Do not forget to Save the changes.

Application Deployment

1. Now I can deploy my project to the prepared environment.

As an example, here is the code of our application, intended to test the connection to our MongoDB node.

MongoManager.java :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package example;
 
import com.mongodb.*;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
 
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.Properties;
 
public class MongoManager {
 
    static String host, dbname, user, password;
 
    public void addData(int repeats) {
        try {
 
            Properties prop = new Properties();
            prop.load(new FileInputStream(System.getProperty("user.home") + "/mydb.cfg"));
 
            host = prop.getProperty("host").toString();
            dbname = prop.getProperty("dbname").toString();
            user = prop.getProperty("user").toString();
            password = prop.getProperty("password").toString();
 
            System.out.println("host: " + host + "\ndbname: " + dbname + "\nuser: " + user + "\npassword: " + password);
 
            MongoCredential credential = MongoCredential.createCredential(user, dbname, password.toCharArray());
            MongoClient mongoClient = new MongoClient(new ServerAddress(host), Arrays.asList(credential));
 
            MongoDatabase db = mongoClient.getDatabase(dbname);
 
            try {
                db.getCollection("mycollection");
            } catch (Exception e) {
                db.createCollection("mycollection", null);
                System.out.println("Repeats: " + repeats);
                for (int i = 1; i <= repeats; i++) {
                    Document document = new Document("data", new Date());
                    db.getCollection("mycollection").insertOne(document);
                    System.out.println("INFO: row added " + document);
                }
            } finally {
                mongoClient.close();
            }
        } catch (IOException ex) {
        }
    }
}

2. Any application can be deployed using either Cloudjiffy Deployment Manager (with a local file/URL as a source) or Maven (for deployment from GIT/SVN).

For testing, I can try our ready-to-use mongoclient.war project, which already contains the appropriate connector driver (or download its sources and adjust it in any preferred way).

  

Note: To connect my own project to my MongoDB database, I need to upload the appropriate mongo-java-driver .jar library to the webapps/{app_context}/WEB-INF/lib folder of my app server with the deployed application.

3. As a result, I’ll get an environment similar to the one below:

  

Connection Check-Up

1. Click Open in Browser next to the environment with our example app deployed. I’ll see a new window opened with the simple MongoDB Manager form shown.

                                                          

Type the desired number of rows (for being added to the corresponding database) into the appropriate field and click the Insert rows button.

2. Wait a moment until the page stops updating and return to the MongoDB admin panel.

Navigate to the mongodb-connect database within the list to the left and check for the new my-collection inside - it should include the above-stated amount of records, 5 in our case.

As I can see, everything works fine, as an application could connect to our DB. Now use the admin panel to perform any other required operations to the database in a similar way.

 


Was this article helpful?

mood_bad Dislike 0
mood Like 0
visibility Views: 15070