Call MongoDB function from Java

You can do all this with java driver.

MongoClient mongoClient = new MongoClient();
MongoDatabase mdb = mongoClient.getDatabase("TestDB");

/* run this <code snippet> in bootstrap */
BsonDocument echoFunction = new BsonDocument("value",
        new BsonJavaScript("function(x1) { return x1; }"));

BsonDocument myAddFunction = new BsonDocument("value",
        new BsonJavaScript("function (x, y){ return x + y; }"));

mdb.getCollection("system.js").updateOne(
        new Document("_id", "echoFunction"),
        new Document("$set", echoFunction),
        new UpdateOptions().upsert(true));

mdb.getCollection("system.js").updateOne(
        new Document("_id", "myAddFunction"),
        new Document("$set", myAddFunction),
        new UpdateOptions().upsert(true));

mdb.runCommand(new Document("$eval", "db.loadServerScripts()"));
/* end </code snippet> */

Document doc1 = mdb.runCommand(new Document("$eval", "echoFunction(5)"));
System.out.println(doc1);

The result is also:

Document{{retval=5.0, ok=1.0}}

Tags:

Java

Mongodb