title: Connection to MongoDB by SSH in Java
body: <p>To connect to MongoDB from Java I use:</p>
  
  <pre><code>MongoClient mongoClient = new MongoClient("localhost", port);
  </code></pre>
  
  <p>And it works fine. Now I would like to connect to MongoDB which is on machine where I have to login by SSH. I try to use <a href="http://www.jcraft.com/" rel="nofollow noreferrer">JSch</a> for this, here is my code:</p>
  
  <pre><code>String host = "host";
  String user = "user";
  String password = "pass";
  int port = 22;
  
  int tunnelLocalPort = 3309;
  String tunnelRemoteHost = "host";
  int tunnelRemotePort = 3306;
  
  JSch jsch = new JSch();
  Session session = jsch.getSession(user, host, port);
  session.setPassword(password);
  localUserInfo lui = new localUserInfo();
  session.setUserInfo(lui);
  session.connect();
  session.setPortForwardingL(tunnelLocalPort, tunnelRemoteHost, tunnelRemotePort);
  </code></pre>
  
  <p>Everything looks fine, I can connect, but here is a problem:</p>
  
  <pre><code>MongoClient mongoClient = new MongoClient("localhost", 27020);
  List&lt;String&gt; databaseNames = mongoClient.getDatabaseNames();
  LOG.info("DB names=" + databaseNames);
  </code></pre>
  
  <p>And error is:</p>
  
  <pre class="lang-none prettyprint-override"><code>Aug 21, 2014 4:12:29 PM com.mongodb.DBTCPConnector initDirectConnection
  Warnung: Exception executing isMaster command on localhost/127.0.0.1:27020
  java.io.IOException: couldn't connect to [localhost/127.0.0.1:27020] bc:java.net.ConnectException: Connection refused: connect
      at com.mongodb.DBPort._open(DBPort.java:214)
  </code></pre>
  
  <p>Should I set something more to connect? How can I check from Java that program connects, when I check <code>session.isConnected()</code> output is <code>true</code>. When I use PuTTY everything works fine.</p>