How to execute MongoDB js script using Java MongoDriver

I implemented the JavaScript function inside the Mongodb server using this example .

It works fine when I use mongo shell, but I want to run it from a Java program. This is the code:

public String runFunction() {

    CommandResult commandResult1 = db.command("db.loadServerScripts()");
    CommandResult commandResult2 = db.command("echoFunction(3)");

    return commandResult2.toString();
}

I do not understand the result.

+4
source share
3 answers

You should use DB.eval (), see api docs and make sure that you are not concatenating strings. Pass variables instead.

I think your answer is probably the same answer as the fooobar.com/questions/1583073 / ... .

+1
source

MongoDB 3.4+. 3.4 - BasicDBObject Database.runCommand(). .

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);
+2
@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 a workaround depending on your requirements.

+1
source

All Articles