bartektartanus
bartektartanus

Reputation: 16080

How to run js file in mongo using spring data

In mongo shell js file can be run using load command:

load("path/to/file/file.js")

How to do this using spring-data? Or any other way in Java. I've tried:

BasicDBObject obj = new BasicDBObject();
obj.append( "$load" , "/path/file.js" );
CommandResult t=mongoTemplate.executeCommand(obj);

and:

obj.append( "$eval" , "load(\"/path/file.js\")" );

but it doesn't work.

Upvotes: 9

Views: 10182

Answers (2)

Oliver Drotbohm
Oliver Drotbohm

Reputation: 83081

Here's the relevant section of the reference docs on how to work with scripts in Spring Data MongoDB.

ScriptOperations scriptOps = template.scriptOps();

// Execute script directly
ExecutableMongoScript echoScript = new ExecutableMongoScript("function(x) { return x; }");
scriptOps.execute(echoScript, "directly execute script");     

// Register script and call it later
scriptOps.register(new NamedMongoScript("echo", echoScript)); 
scriptOps.call("echo", "execute script via name");    

Upvotes: 12

rsutormin
rsutormin

Reputation: 1649

What if you read text of your JavaScript from the file manually and put it into $eval? Something like:

    StringBuilder text = new StringBuilder();
    BufferedReader br = new BufferedReader(new FileReader(
            new File("/path/file.js")));
    try {
        while (true) {
            String line = br.readLine();
            if (line == null)
                break;
            text.append(line).append("\n");
        }
    } finally {
        try { br.close(); } catch (Exception ignore) {}
    }
    BasicDBObject obj = new BasicDBObject();
    obj.append("$eval", text.toString());
    System.out.println(mongoTemplate.executeCommand(obj));

If it works then check that your file is accessible in server-side file system. Because load() is executed on server side.

Upvotes: 4

Related Questions