In MongoDB shell one can use db.loadServerScripts() command to load all scripts in the system.js collection for the current database. Then one can use functions in system.js collection for map-reduce or $where.
For example:
foo = function (parameters) .................foo code..................
db.system.js.save( { _id : "foo", value : foo } );
Now one can use foo in map-reduce.
How can I define a foo function to use it in a map-reduce using Java driver?
mapReduceor byeval()) then you can reference that code and use it. Something like.loadServerScripts()only works in the shell because it is itself a JavaScript REPL, and therefore understands JavaScript. So this is reall of no use to you in another language, unless you similarly want to load in a JavaScript runtime. In all likelihood, the "how you intend to use your 'sum'" would also not be valid, and therefore you would code the real solution differently.$whereor mapReduce, but you still need to send basic JavaScript code ( either special object for driver or just a string as argument, driver dependant ) as the basic "meat" of either the$whereor mapReduce invocation itself. So for the driver driver ( according to documentation ) the arguments for JavaScript code would be aString.