How do I execute a MongoDB js script using the Java MongoDriver

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);

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.


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/

Tags:

Java

Mongodb