Executing custom function on MongoDB using Casbah/Scala

折月煮酒 提交于 2019-12-06 11:47:06

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
  }
}

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?).

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