Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I execute a MongoDB js script using the Java MongoDriver

Tags:

java

mongodb

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.

like image 995
Tharanga Avatar asked Apr 17 '15 16:04

Tharanga


People also ask

How does MongoDB connect to Java code?

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'.

What is Run command in MongoDB?

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.

Is MongoDB compatible with Java?

All features are supported.


1 Answers

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);
like image 107
Prof Mo Avatar answered Oct 12 '22 20:10

Prof Mo