0

I'm trying to make a design decision.

I'm not well acquainted with either MongoDB or its PHP driver but I'm intrigued by the JavaScript syntax of the stored functions that mongodb use.

Can you tell me whether there is a way to create MongoDB stored functions using PHP?

My reference for creating mongodb stored functions: https://github.com/mongodb/mongo/blob/master/jstests/storefunc.js

1 Answer 1

2

It sounds like you are referencing server-side functions.

Creating / updating a server-side function is as easy as updating the system.js collection:

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

The problem here is really "using" the server-side functions. First you have to write some kind of awkward update/insert statements. Second, these are not stored procedures. They are not compiled for speed with the intent of running them on the server.

If you use a server-side function for querying it won't use indexes for anything inside of that function. Plus it will use the eval feature under the hood which can lock up your DB.

Also, there are no triggers, so you can't use these for triggers either.

Overall, there is not a lot of use for server-side functions, which is probably why they get 3 paragraphs in the docs.

If you need advanced query functions look at the new Aggregation Framework. If you're looking for some form of triggers, you will have to roll your own. If you're looking for stored procedures, these are really not it.

Sign up to request clarification or add additional context in comments.

6 Comments

Hm. If it's such a mess why does it actually exist? Is there any scenario where only server-side function can be used to solve a problem?
I think it's one of those things that was created when they thought it could be the next stored procedure. But the dream was really dashed by the fact that they can only have one instance of the javascript interpreter at a time. Worth remembering that MongoDB is only a couple of years old and they don't have enough people to really update the docs.
Just one more thing: I read on mapReduce Are all of the fallbacks you describe applied to mapReduce as well?
A MongoDB instance can only run one Map/Reduce at a time. (again only one javascript engine) This is one of the big drivers for the Aggregation Framework from 2.1.
Thank you. I found an alternative way of doing what I aimed using the mapReduce: dba.stackexchange.com/q/15517/7652 by storing a closure in the document :)
|

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.