1

There are a couple of examples of how to create "stored procedures" in MongoDB (here is one) but they only show how to add the code directly, for example in the mongo shell. For any nontrivial stored procedure one would want to store the code in a .js file and 'import' the file into MongoDB. That way it can be easily edited, versioned, etc.

Is there a way to do this?

3
  • What are you trying to accomplish? (Using the technique in the linked blog post is specifically not recommended by 10gen : docs.mongodb.org/manual/applications/server-side-javascript) Running JS within the DB isn't recommended in MongoDB currently. It's not designed with a "Stored Procedure" model. Commented Feb 14, 2013 at 21:03
  • I would like to call a single mongodb function from my webserver, that performs multiple queries before returning a final result, without having to go in and out of the database because of interim data. It's odd that 10gen discourages this practice and then provides nice documentation and api support to do it. Commented Feb 14, 2013 at 21:27
  • Its not "nice", you must use eval which is not a native API for the execution of JS functions, it is much like hacking it to do something it isn't supposed to using a global lock and function which can't be used across shards. Stored procedures are so rarely needed and so frequently abused in databases that support them. I would make sure that you actually get any performance at all from using them. As for getting them to work, I am unsure how you can performantly atm. Commented Feb 14, 2013 at 21:54

1 Answer 1

3

You can use following syntax:

$ mongo mydb import.js

And writing import instructions inside a script, i.e:

var myfunc = function(x, y){ return x + y; }}

db.system.js.save({_id:"myfunc", value: myfunc);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.