title: Call MongoDB function from Java
body: <p>I'm trying to call a stored JavaScript function from the MongoDB Java driver.</p>
  
  <p>I have been following this guide to store the function on the DB server and I'm able to call the function from the mongo shell and have the result returned.</p>
  
  <p>However I cannot figure out how to call the same function in Java?</p>
  
  <p>According to this <a href="http://api.mongodb.org/java/current/com/mongodb/DB.html#doEval-java.lang.String-java.lang.Object...-" rel="noreferrer">http://api.mongodb.org/java/current/com/mongodb/DB.html#doEval-java.lang.String-java.lang.Object...-</a> there's a method called <code>doEval</code> </p>
  
  <p>I have also tried to use it with this method:</p>
  
  <pre><code>public static String callFunction() {
  
      try (MongoClient client = new MongoClient("localhost")) {
          com.mongodb.DB db = client.getDB("TestDB");
          return db.doEval("echoFunction", 3).toString();
      }
  }
  </code></pre>
  
  <p>But when I call the method this is what I get:</p>
  
  <pre><code>{ "retval" : { "$code" : "function (x) {\n    return x;\n}"} , "ok" : 1.0}
  </code></pre>
  
  <p>and I would expect to get the number 3 back in this case.</p>
  
  <p>Another problem with the above code is that the method <code>client.getDB()</code> is deprecated. As I understand it the new method to call is <code>client.getDatabase()</code> and it returns a <code>MongoDatabase</code> object, but according to the <a href="http://api.mongodb.org/java/current/com/mongodb/client/MongoDatabase.html" rel="noreferrer">API</a> there is no method to execute a function.</p>
  
  <p>So my question is: Is it possible to execute a stored JavaScript function on the database server from Java and get back the result of that function? And if it is possible, I would appreciate some help on how to do it?</p>
  
  <p>Thank you.</p>
  
  <p><strong>Edit:</strong></p>
  
  <p>According to a comment on <a href="https://stackoverflow.com/questions/27332979/calling-server-js-function-on-mongodb-from-java?rq=1">Calling server js function on mongodb from java</a>: </p>
  
  <blockquote>
    <p>"It seems like getNextSequence is a function written in the mongo
    javascript shell. Neither the database (mongod) nor the Java side
    knows this function exists and neither is able to interprete the
    Javascript code the function contains. You will have to reimplement it
    in Java. "</p>
  </blockquote>
  
  <p>The function I'm trying to implement is a bit more complex than the example above - it's supposed to return a collection of documents and that does not seems to be working using the db.doEval method. </p>
  
  <p>So I guess the comment is correct?</p>