I am trying to call a JavaScript stored function from the MongoDB Java driver.
I follow this guide to save the function on the database server, and I can call the function from the mongo shell and return the result.
However, I cannot figure out how to call the same function in Java?
According to this http://api.mongodb.org/java/current/com/mongodb/DB.html#doEval-java.lang.String-java.lang.Object...- there is a method called doEval
I also tried using it with this method:
public static String callFunction() { try (MongoClient client = new MongoClient("localhost")) { com.mongodb.DB db = client.getDB("TestDB"); return db.doEval("echoFunction", 3).toString(); } }
But when I call the method, this is what I get:
{ "retval" : { "$code" : "function (x) {\n return x;\n}"} , "ok" : 1.0}
and I would expect to return number 3 in this case.
Another problem with the code above is that the client.getDB() method is deprecated. As I understand it, the new method to call is client.getDatabase() , and it returns a MongoDatabase object, but according to the API there is no method to execute the function.
So my question is: is it possible to execute a stored JavaScript function on a database server with Java and return the result of this function? And if possible, I would appreciate help in how to do this.
Thanks.
Edit:
According to the comment , the server js function call on mongodb from java :
"It seems getNextSequence is a function written in mongo javascript shell. Neither the database (mongod) nor the Java side knows that this function exists, and none of them can interpret the Javascript code that the function contains. You will have to redefine it in Java. "
The function I'm trying to implement is a bit more complicated than the example above - it should return a collection of documents and doesn't seem to work using the db.doEval method.
So, I think the comment is correct?