Working With Stored JavaScript in MongoDB
05 April 2010Stored JS in MongoDB is saved in the special system.js collection. The documents there should be structured like:
_id is the name of the function, and value is the JS code defining the function. Here’s an example of saving such a function and then using it in an eval. This can be run using the MongoDB shell:
Once sum
is defined we can use it from all of MongoDB’s JS
contexts, including Map/Reduce and $where. In this example we use
sum
within a $where clause to get all documents where the
sum of x and y is 6:
Since system.js is a collection, we can perform normal MongoDB operations on it in order to administer our stored JS functions. We might want to list the stored functions:
or remove a function we previously stored:
Stored JS and PyMongo
In version 1.5 PyMongo added some
helpers to make working with stored JS incredibly easy. The API is
accessed through the Database.system\_js
property, which
returns an instance of the SystemJS helper
class.
The SystemJS class allows us to add, call, and remove stored JS
functions using a nice Pythonic interface:
The
implementation
of the SystemJS class is actually pretty trivial. The trickiest bit is
getting the argument passing right between the Python lambda returned by
*getattr*
and the invocation of the stored JS function
within the eval.