Call mongodb function from Java
I'm trying to call stored JavaScript functions from the mongodb Java driver
I have been following this guide to store this function on the DB server. I can call this function from the Mongo shell and return the result
But I can't 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 named doeval
I have also tried 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 this method, this is what I get:
{ "retval" : { "$code" : "function (x) {\n return x;\n}"},"ok" : 1.0}
In this case, I hope to get number 3
Another problem with the above code is that the client. Method is not recommended getDB(). As far as I know, the new method called is client Getdatabase (), which returns a mongodatabase object, but according to the API, there is no method to execute the function
So my question is: can I execute the stored JavaScript function from Java on the database server and get the result of the function? If possible, I would like to thank you for how to do this?
thank you.
Edit:
According to the comments of calling server JS function on mongodb from Java:
The function I'm trying to implement is a little more complex than the above example - it should return a collection of documents and doesn't seem to use dB Doeval method
So I think the comment is correct?
Solution
You should do this:
return db.doEval("echoFunction(3)").toString();
If you only use function names in Eval, you can only reference JavaScript variables that store function code on the server side It will not execute it When you use parentheses, you request that a function be actually executed If you need to send something more complex than numbers, I recommend using a JSON serializer