Luis Felipe Garcia
Luis Felipe Garcia

Reputation: 168

Call stored function mongodb java driver

I have a problem executing stored function on MongoDB from my java code , i have a stored function like this.

db.system.js.save({

  _id:"myFunction",
  value:function(data){
    //todo        
    return 1 + 1;
   }
});

And in my java code :

mongoClient = new MongoClient(SERVER, PORT); // should use this always
db = mongoClient.getDB(DB);
DBObject datos = new BasicDBObject();
datos.put("val", "myvalue");

Then i am trying to execute the function:

try 1

db.doEval("myFunction", datos);

try 2

db.eval("myFunction", datos);

try 3

DBObject query = new BasicDBObject();
query.put("myFunction", datos);
db.command(query);

But the stored function does not execute, any ideas ?

Upvotes: 0

Views: 1131

Answers (1)

Luis Felipe Garcia
Luis Felipe Garcia

Reputation: 168

I solved, it seems to pass values/objects to the stored function you have to serialize the object as JSON, so I did this :

String values = JSON.serialize(datos);

Then my java code looks like :

CommandResult er = db.doEval("myFunction("+values+")");

And the stored function gets executed correctly.

Upvotes: 1

Related Questions