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,
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?).
来源:https://stackoverflow.com/questions/10159475/executing-custom-function-on-mongodb-using-casbah-scala