Alternative of eval() command in Java

Hello everyone,

I stored some procedures in MongoDB and want to get them using Java code.

Here is my code:

    	public static String runFunction() {
    		@SuppressWarnings("resource")
    		MongoClient mongoClient = new MongoClient("localhost");
    		@SuppressWarnings("deprecation")
    		DB db = mongoClient.getDB("test");
    		System.out.println("Connected");
    	    CommandResult commandResult1 = db.command("db.loadServerScripts()");
    	    String str = "getCards(2)";
    	    CommandResult commandResult2 = db.command(str);
    	    System.out.println(commandResult2.toString());
    	    return commandResult2.toString();
    	}

and I am getting error

> { "ok" : 0.0 , "errmsg" : "no such command: 'getCards(2)'" , "code" : 59 , "codeName" : "CommandNotFound"}

Where as if I use mongo shell it is working over there. Is there is any alternative of this? Kindly help me out.

Thanks in advance.

Stored JavaScript functions are not the equivalent of server-side stored procedures and cannot be directly invoked from your Java code. These functions are only useful in a JavaScript execution context (for example, the mongo shell or Map/Reduce).

The db.loadServerScripts() command in the mongo shell eval()s saved scripts into the current shell session so those functions can be invoked client-side. The server eval command has been deprecated since MongoDB 3.0 and removed as of MongoDB 4.2. It had serious performance and security consequences and should not be used.

You should write your queries using the Java driver. See the Java driver tutorials for more examples.

I strongly recommend you sign up for the free M220: MongoDB for Java Developers course at MongoDB University. The latest session just started this week, so if you join now you can get started with lessons and assignments that will accelerate your learning around the essentials of creating a Java application using MongoDB.

Regards,
Stennie

3 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.