Executing custom function on MongoDB using Casbah/Scala

房东的猫 提交于 2019-12-08 00:46:31

问题


I've defined a function in MongoDB using its command line client.

function something(){...}

I was wondering how can I execute a custom MongoDB function using casbah from Scala.

Any recommendations ?

Thanks,


回答1:


There are a few ways to run arbitrary javascript code on the server. You can supply it as a string from the client and send it to the server for evaluation, or install the function on the server first, as documented here: http://docs.mongodb.org/manual/core/server-side-javascript/

Server-side functions are registered per db, in a collection called system.js.

Either way, you can then use the the db.eval() command to call your code, as shown here:

/* Call like so:
     evalJavascript(myDB, "function (oid) { return coll.find({_id: oid}); }", someObjectId)
*/
def evalJavascript(db:MongoDB, func: String, args: String*): Validation[String, Object] = {
  val result = db.command(Map(
    "eval" -> func,
    "args" -> args.toList
  ));

  if (result.ok) {
    result.get("retval").success
  } else {
    result.getErrorMessage().failure
  }
}



回答2:


Are you talking about MapReduce jobs, written in JavaScript? If so, you can use .mapReduce(...) method of collection, but you need to specify map, reduce and finalize functions.
Here is the example.

If you're talking about executing arbitrary JavaScript code, I think it is not possible (why don't you use scala for object manipulations?).



来源:https://stackoverflow.com/questions/10159475/executing-custom-function-on-mongodb-using-casbah-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!