Creating Stored Procedures in MongoDB with Stored Javascript

Introduction

If you’re working with MongoDB and looking for a how to use stored procedures, you might have a little trouble getting started because MongoDB doesn’t have an exact equivalent to stored procedures but it does offer a feature stored javascript that offers similar functionality. You can store Javascript logic inside of a special collection and use that logic when needed. In this article we’ll show you a simple example of storing a javascript function that you can re-use. You should be able to apply what you learn here to your specific situation. We hope you find this instruction useful because the official MongoDB doesn’t provide useful examples. That being said let’s jump straight into the tutorial.

If you’re coming from a SQL background where you know exactly how to implement stored procedures, using MongoDB stored javascript can feel like a bit of a departure but we find it quite easy. First of all we found it refreshing to write our stored procedures in Javascript which is becoming increasingly popular and second-nature to most developers.

Prerequisites

  • You should have MongoDB installed and running
    • If you don’t have it running try the mongod command in your terminal.
  • It’s not required but it’s recommended that you have some previous command line experience.

How to implement Stored Procedures with Stored Javascript

We’ll begin with the tried and true example of creating a function that simply adds two numbers together. It takes in two arguments and returns their summation. Let’s first write the function in plain vanilla javascript.

function sum(x,y) {
    return x+y;
}

Now let’s say this is functionality that we were using often within MongoDB and finally made the decision to convert it to a stored procedure, or as we implement it in MongoDB, stored javascript.

Where do we store the Javascript Function?

You might already be asking yourself “Ok, I have this function, but where do I put it?”. MongoDB provides a special collection on every database called system.js where you can put your custom javascript functions.

Saving the function inside the db.system.js collection

Now to save our add function inside this collection we will execute the following in the Mongo Shell:

db.system.js.save({_id: "sum", value: function(x,y) { return x+y;}});

Notice we have moved the function name into the _id field and the function definition without the function name into the value field.

When you execute this command you should get a response like below confirming that the function was saved inside the collection:

WriteResult({ "nMatched" : 0, "nUpserted" : 1, "nModified" : 0, "_id" : "sum" })

Now how do I use it?

Note: A lot of tutorials will show you how to use it with the eval command but eval has been deprecated.

Now that we have the function stored in the proper collection db.system.js, we want to use the function. Let’s first put some data in a collection so we can test it:

>db.test.save({x: 4, y: 2});
WriteResult({ "nInserted" : 1 })
>db.test.save({x: 4, y: 2});
WriteResult({ "nInserted" : 1 })
>db.test.save({x: 100, y: 2});
WriteResult({ "nInserted" : 1 })

Now let’s use the function our stored sum function in a $where qualifier to check for the documents where x & y add up to 6. We should get the first two documents I inserted back.

> db.test.find({$where: "sum(this.x, this.y) == 6"});
{ "_id" : ObjectId("5cf698db86d331b7a14adf38"), "x" : 4, "y" : 2 }
{ "_id" : ObjectId("5cf698df86d331b7a14adf39"), "x" : 4, "y" : 2 }

Viewing all stored procedures

Because it’s important for a developer to view what stored javascript already exist we’ll quickly show you how to view your stored procedures. Remember that the db.system.js is just a collection so you can execute the find command to see everything in it:

> db.system.js.find()
{ "_id" : "sum", "value" : { "code" : "function (x,y) { return x+y;}" } }

We find the previous command a little hard to read so we use the following query to list the distinct functions:

> db.system.js.distinct("_id");
[ "sum" ]

Conclusion

In this article we showed you how to create similar functionality to a stored procedure using stored javascript in MongoDB. We hope you take this as a starting point to utilizing stored javascript that saves you loads of time. As always if you have any database needs or are moving to a production environment and want somebody else to handle the complexity that arises, please don’t hesitate to reach out to Object Rocket.

Pilot the ObjectRocket platform free for 30 Days

It's easy to get started. Imagine the time you'll save by not worrying about database management. Let's do this!

PILOT FREE FOR 30 DAYS

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.