Store a JavaScript Function on the ServerΒΆ


We do not recommend using server-side stored functions if possible.

There is a special system collection named system.js that can store JavaScript functions for reuse.

To store a function, you can use the db.collection.save(), as in the following example:

     _id : "myAddFunction" ,
     value : function (x, y){ return x + y; }
  • The _id field holds the name of the function and is unique per database.
  • The value field holds the function definition

Once you save a function in the system.js collection, you can use the function from any JavaScript context (e.g. eval command or the mongo shell method db.eval(), $where operator, mapReduce or mongo shell method db.collection.mapReduce()).

Consider the following example from the mongo shell that first saves a function named echoFunction to the system.js collection and calls the function using db.eval() method:

                   { _id: "echoFunction",
                     value : function(x) { return x; }

db.eval( "echoFunction( 'test' )" )

See http://github.com/mongodb/mongo/tree/master/jstests/storefunc.js for a full example.

New in version 2.1: In the mongo shell, you can use db.loadServerScripts() to load all the scripts saved in the system.js collection for the current database. Once loaded, you can invoke the functions directly in the shell, as in the following example:



myAddFunction(3, 5);