2

Is there a way in mongo to create user-defined Javascript functions. I have several Map/Reduce functions on the client side that i would like to use within other MR functions.

For example, several MR functions calculate all sorts of averages. I want to be able to use them like so :

function reduce(k,v)
{
    if (val > myDatabaseAverage())
    // ..do something
}

2 Answers 2

11

Use

db.system.js.save( { _id : "myDatabaseAverage" , value : function(){
  // ..do something 
} } );

That will store the JS function on the server and can be accessed by m/r from that point on.

For further examples see : mongo/jstests/core/mr_stored.js

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

2 Comments

should it not be "myDatabaseAverage" instead?
The mongo tests use db.system.js.insert() now.
0

As mentioned by @Remon van Vliet,

You will have to use,

db.system.js.save( { _id : "myDatabaseAverage" , 
                     value : function(){ // ..do something } 
                 } );

to save your function first,

and then you need to call,

db.loadServerScripts();

before you execute your function.

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.