Mongodb Stored Javascript Functions - Ruby Edition
I was writing a couple of different analytics applications recently. My applications did two different things but accessed the same database. I was wondering if there were a way to store javascript functions so that I could share code between two different applications. That's when I stumbled across the server side code execution and Mike Dirolf's post on stored javascript and pymongo. I was hoping for the same type of functionality in the ruby driver as in pymongo, but alas it wasn't.
In the patch that I submitted to the mongo ruby driver, I added a couple of functions that will allow you to add stored Javascript functions to system.js in your database. Let's walk through a use case:
# Assume we're using the mongo driver and db = test
db = Mongo::Connection.new("localhost").db("test")
# Setup the stored function in MongoDB
db.add_stored_function("sum", "function (x, y) { return x + y; }")
sites = db.collection("sites")
sites.insert({:name => "Site 1", :admin_count => 2, :moderator_count => 3})
sites.find("$where" => "sum(this.admin_count, this.moderator_count) == 5")
# When we don't need the stored function any more
db.remove_stored_function("sum")
This is just one example of how to use the stored functions. Don't forget that you can use them in map/reduce, eval, and $where clauses.
Unlike the pymongo version, I did not create an instance of the system.js collection in the db instance. This would have allowed us to use introspection to actually make method calls instead of having to write out an eval method. (See how it works for pymongo at the end of Mike's post.) In my use cases, I used the stored functions within where and map_reduce calls and didn't really need to use eval. If other people need it, I could definitely change it up.
Posted 7/09/2010 11:47:00 AM - mongodb
WHO AM I?
I'm Rimas Silkaitis, a mild mannered Ruby dev living in San Francisco. I like building stuff for the web and am particularly interested in machine learning. I also own a set of turntables.
Posts

