Although it’s not recommended to store your application logic in MongoDB, it’s sometimes useful to create Javascript functions for database management purposes in the database.
The process is really easy. MongoDB has a special collection named system.js, that can contain Javascript functions. Creating a function in MongoDB is as simple as inserting a record with the name and the function code into the fields named _id and value in this collection.
Example:
db.system.js.save(
{
_id : "myFirstFunction" ,
value : function (a, b){ return a + b; }
}
);
The function is now accessible in any Javascript context (for instance in a $where). If you need to access the functions from the MongoDB shell, call the command db.loadServerScripts() to load them for the current database.