Home:ALL Converter>How can I set the directory of a MongoDB database in a Java application?

How can I set the directory of a MongoDB database in a Java application?

Ask Time:2017-07-23T22:43:47         Author:Edoardo Baral

Json Formatter

I recently decided to learn the foundamentals of using MongoDB in Java applications but I have some problems and doubts to resolve. I hope someone can help me. I wrote a little Java application to read and write data in a local Mongo database (I'm using mongo-java-driver-3.3.0.jar on Windows 10). I have installed MongoDB in the directory C:\Program Files\MongoDB. Can anyone tell me if is possible to create my test database in a specific directory (for example D:\Database)? Thank you.

package test;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.client.MongoDatabase;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
import java.util.Arrays;

public class MongoDBJDBC 
{
   public static void main( String args[] ) 
   {
      try
      {
         // Connection to the MongoDB server
         MongoClient mongoClient = new MongoClient("localhost" , 27017);

         // Connection to the database
         MongoDatabase db = mongoClient.getDatabase("test");
         System.out.println("Connect to database successfully");

      }
      catch(Exception e)
      {
         System.err.println( e.getClass().getName() + ": " + e.getMessage() );
      }
   }
}

Author:Edoardo Baral,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/45266345/how-can-i-set-the-directory-of-a-mongodb-database-in-a-java-application
yy