Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 478
bartektartanus Avatar asked Sep 09 '15 18:09

bartektartanus


People also ask

How do I run a JavaScript file in Mongo shell?

Load JavaScript file js file from mongo shell, using the load() function. load() function allow to execute from absolute and relative paths. We can simply load a file in mongo shell with load() function.

Can we use spring data JPA with MongoDB?

Yes, DataNucleus JPA allows it, as well as to many other databases.

How MongoDB read data in spring boot?

Read operations using Spring Boot MongoDBFetch all the documents (grocery items) using the findAll() method. Get a single item (document) by its name field using the findItemByName method. Get a list of items based on a category.


2 Answers

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");    
like image 118
Oliver Drotbohm Avatar answered Oct 07 '22 11:10

Oliver Drotbohm


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.

like image 24
rsutormin Avatar answered Oct 07 '22 12:10

rsutormin