I have implemented a JavaScript function inside the Mongodb server using this example.
It works fine when I use mongo shell, but I want to run it from inside 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 don't understand the result.
To connect: MongoClient client = MongoClients. create("<<MongoDB URI>>"); To connect to MongoDB on your local instance and default port, you can just omit the URI part of the above, or use a URI like 'mongodb://localhost:27017'.
db.runCommand(command) Provides a helper to run specified database commands. This is the preferred method to issue database commands, as it provides a consistent interface between the shell and drivers. Parameter. Type.
All features are supported.
The previous answers does not work in MongoDB 3.4+. Th proper way to do this in version 3.4 and above is to create a BasicDBObject and use it as the parameter of Database.runCommand(). Here's an example.
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);
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