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.
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.
Yes, DataNucleus JPA allows it, as well as to many other databases.
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.
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");
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With