Mongo用户定义函数和Map Reduce

时间:2022-03-16 02:31:31

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.

有没有办法在mongo中创建用户定义的Javascript函数。我在客户端有几个Map / Reduce功能,我想在其他MR功能中使用。

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

例如,几个MR函数计算各种平均值。我希望能够像这样使用它们:

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

2 个解决方案

#1


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

使用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.

这将把JS函数存储在服务器上,并且可以从那时开始通过m / r访问。

For further examples see : https://github.com/mongodb/mongo/blob/master/jstests/storefunc.js

有关更多示例,请参阅:https://github.com/mongodb/mongo/blob/master/jstests/storefunc.js

#2


As mentioned by @Remon van Vliet,

如@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.

在执行你的功能之前。

#1


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

使用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.

这将把JS函数存储在服务器上,并且可以从那时开始通过m / r访问。

For further examples see : https://github.com/mongodb/mongo/blob/master/jstests/storefunc.js

有关更多示例,请参阅:https://github.com/mongodb/mongo/blob/master/jstests/storefunc.js

#2


As mentioned by @Remon van Vliet,

如@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.

在执行你的功能之前。