This version of the manual is no longer supported. Learn more about upgrading your version of MongoDB.

Store a JavaScript Function on the Server


Do not store application logic in the database. There are performance limitations to running JavaScript inside of MongoDB. Application code also is typically most effective when it shares version control with the application itself.

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

To store a function, you can use the, as in the following examples:
     _id: "echoFunction",
     value : function(x) { return x; }
     _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. $where operator, mapReduce command or db.collection.mapReduce().

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);