Conexão com MongoDB

  1. Acesso o
    Painel de Administração Jelastic
  2. Crie o seu ambiente com uma base de dados MongoDB:
  3. Verifique em sua caixa postal as credenciais fornecidas para acesso à base de dados:
  4. Click Open in browser button for MongoDB. Log in to the admin panel using abovementioned credentials and create new database, for example, mongodbconnection.


  5. Clique no botão Configurar de seu servidor de aplicação (no nosso caso Tomcat 6).
  6. Crie um arquivo mydb.cfg na pasta raiz home e adicione as configurações necessárias:

  7. host=mongodb-{env_name}.{hoster_domain}
    dbname={db_name}
    username={get in the email from Robot@jelastic}
    password={get in the email from Robot@jelastic}

    Importante: Você também pode colocar as configurações de acesso à base de dados em sua aplicação. No nosso exemplo todas as configurações estão no arquivo mydb.cfg que será lido pela aplicação.
  8. Você pode utilizar o exemplo a seguir para ver o mecanismo de conexão com nossa base de dados.

  9. DbManager.java :
    package com;
    
    import com.mongodb.*;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.util.Date;
    import java.util.Properties;
    
    public class MongoManager {
    
        static String host, dbname, user, password;
    
        public void addData(int repeats) {
            try {
                DBCollection dbc = null;
    
                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);
    
                Mongo m = new Mongo(host, 27017);
                DB db = m.getDB(dbname);
                
                if (db.authenticate(user, password.toCharArray())) {
                    System.out.println("Connected!");
                } else {
                    System.out.println("Connection failed");
                }
    
                try {
                    db.getCollection("mycollection");
                } catch (Exception e) {
                    db.createCollection("mycollection", null);
                } finally {
                    System.out.println("Repeats: " + repeats);
                    for (int i = 1; i <= repeats; i++) {
                        BasicDBObject data = new BasicDBObject("data", new Date());
                        db.getCollection("mycollection").save(data);
                        System.out.println("INFO: row added " + data);
                    }
                }
            } catch (IOException ex) {
            }
        }
    }
    
    

  10. O próximo passo é fazer o upload do seu arquivo .war pelo Gerenciador de Instalação. Em nosso exemplo o arquivo utilizado foi o mongodbmanager.war (clique nele para fazer o download) contendo o conector jdbc-connector.
    Se preferir, clique em mongodbmanager para baixar o pacote com os fontes do nosso projeto de exemplo.
  11. Instale o arquivo WAR em seu ambiente.
  12. Clique em Abrir no Navegador para inserir linhas em sua base de dados.
  13. Clique em Abrir no Navegador para verificar, no Gerenciador da Base de Dados, se a tabela foi criada.

Create Environment

You can use our one-click installation widget to get the ready-to-go environment with MongoDB inside just in a few clicks:


or follow the manual instruction below:

1. Log in to your Jelastic account.

2. Create an environment with MongoDB instance (available within the NoSQL section). The preferred application server for your 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 your environment to appear at the dashboard.

MongoDB Configurations

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

2. Click the Open in browser button for the MongoDB node within your 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, you need to create a user for this DB - thus, navigate to the Execute tab and choose your 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 - desired name of your new DB user
  • password - password for this user
  • db_name - 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 you can specify all the required for connection data directly in your 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 your 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 browser next to your 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} - name of the DB user you’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 you can deploy your 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 :

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 Jelastic Deployment Manager (with a local file/URL as a source) or Maven (for deployment from GIT/SVN).

For testing, you 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 your own project to your MongoDB database, you need to upload the appropriate mongo-java-driver .jar library to the webapps/{app_context}/WEB-INF/lib folder of your app server with the deployed application.

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

Connection Check Up

1. Click Open in Browser next to your environment with our example app deployed. You’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 mycollection collection inside - it should include the above stated amount of records, 5 in our case.

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

Useful to Know

Jelastic documentation also contains a number of auxiliary guides for the MongoDB server, that may become useful even for the subject-familiar and experienced users:

  • set up the Master-Slave Replication in order to increase your DB efficiency and accessibility of the data it comprises
  • ensure information safety through adjusting the Backups Scheduling - this prevents data loss and allows to restore it in case of an unexpected server failure
  • learn how to establish the Remote Access to your database for getting the ability to work with it via any suitable client application, even without the necessity to log in to our dashboard
  • read the Dump Import/Export guide to discover how to manually backup your data within dump files and subsequently restore it from the previously created dumps if necessary