I have implemented a JavaScript function inside the Mongodb server using this example.
It works fine when I use mongo shell, but I want to run it from inside a Java
You should use DB.eval(), see the api docs and make sure that you don't do string concatenation. Pass the variables through instead.
I think your answer is probably the same answer as this other one on StackOverflow.
@Autowired
private MongoOperations mongoOperations;
private final BasicDBObject basicDBObject = new BasicDBObject();
@PostConstruct
private void initialize() {
basicDBObject.put("eval", "function() { return db.loadServerScripts(); }");
mongoOperations.executeCommand(basicDBObject);
}
private void execute() {
basicDBObject.put("eval", "function() { return echoFunction(3); }");
CommandResult result = mongoOperations.executeCommand(basicDBObject);
}
And then you can use something like:
ObjectMapper mapper = new ObjectMapper();
And MongoOperation's:
mongoOperations.getConverter().read(CLASS, DBOBJECT);
Just try to have some workaround depends on your requirements
The previous answers does not work in MongoDB 3.4+. Th proper way to do this in version 3.4 and above is to create a BasicDBObject and use it as the parameter of Database.runCommand(). Here's an example.
final BasicDBObject command = new BasicDBObject();
command.put("eval", String.format("function() { %s return;}}, {entity_id : 1, value : 1, type : 1}).forEach(someFun); }", code));
Document result = database.runCommand(command);
Since MongoDB 4.2 the eval
command is removed (it was deprecated in 3.0).
There is no more way to eval JavaScript scripts into MongoDB from the Java Driver.
See https://docs.mongodb.com/manual/reference/method/db.eval/