How to run js file in mongo using spring data

后端 未结 2 1280
难免孤独
难免孤独 2020-12-18 01:30

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

相关标签:
2条回答
  • 2020-12-18 01:56

    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.

    0 讨论(0)
  • 2020-12-18 02:00

    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");    
    
    0 讨论(0)
提交回复
热议问题