MongoDB javascript传递参数
我有一个关于将MongoDB javascript中的Arument传递给map函数的问题。 目前,我的想法是这样的:MongoDB javascript传递参数,javascript,mongodb,map,arguments,reduce,Javascript,Mongodb,Map,Arguments,Reduce,我有一个关于将MongoDB javascript中的Arument传递给map函数的问题。 目前,我的想法是这样的: var map = function(n) { if(this.x == n){ emit(this.x); } } var reduce = function(key, values) { values.forEach(function(x) { //do something }); return {nd
var map = function(n) {
if(this.x == n){
emit(this.x);
}
}
var reduce = function(key, values) {
values.forEach(function(x) {
//do something
});
return {nd:values};
}
db.smsdb.mapReduce(map(2), reduce, "collection")
db.smsdb.mapReduce(function(){ map.call(this, 2); }, reduce, "collection")
但是当我尝试这样做时,shell返回一个错误“notcode”…所以我猜我没有正确的方法。
如果有人能找到解决这类问题的正确方法,我将非常高兴能找到正确的方法
谢谢您可以这样做:
db.smsdb.mapReduce(function() { return map(2); }, reduce, "collection")
这一行:
db.smsdb.mapReduce(map(2), reduce, "collection")
正在调用map(2)
,结果(undefined
)作为mapReduce
的map函数传递
相反,你可以这样做:
var map = function(n) {
if(this.x == n){
emit(this.x);
}
}
var reduce = function(key, values) {
values.forEach(function(x) {
//do something
});
return {nd:values};
}
db.smsdb.mapReduce(map(2), reduce, "collection")
db.smsdb.mapReduce(function(){ map.call(this, 2); }, reduce, "collection")
更新
上述操作不起作用,因为map
功能在运行mapReduce
map功能的范围内不可用。因此,您必须将其封装为一个函数,该函数可以生成所需的映射函数:
var mapper = function(n) {
function map() {
if(this.x == n){
emit(this.x);
}
}
return map;
};
db.smsdb.mapReduce(mapper(2), reduce, "collection");
我还应该指出,这个解决方案同样有效:
var map=function(){
if(this.x==n){
发射(这是x);
}
}
mapReduce(映射器,reduce,{out:“nodes”,作用域:{n:2})代码>Mapreduce中的范围表示Mapreduce中的全局参数
正如@Dave Griffith所指出的,您可以使用mapReduce
函数的scope参数
我有点费劲想弄清楚如何正确地将它传递给函数,因为正如其他人所指出的,文档不是很详细。最后,我意识到mapReduce
需要3个参数:
map function
reduce function
object with one or more of the params defined in the doc
Eventually, I arrived at the following code in Javascript:
// I define a variable external to my map and to my reduce functions
var KEYS = {STATS: "stats"};
function m() {
// I use my global variable inside the map function
emit(KEYS.STATS, 1);
}
function r(key, values) {
// I use a helper function
return sumValues(values);
}
// Helper function in the global scope
function sumValues(values) {
var result = 0;
values.forEach(function(value) {
result += value;
});
return value;
}
db.something.mapReduce(
m,
r,
{
out: {inline: 1},
// I use the scope param to pass in my variables and functions
scope: {
KEYS: 1,
sumValues: 22// of course, you can pass function objects too
}
}
);
我发现您的代码有一个错误,它说reference error:map未定义。你确定这样行吗?真奇怪。这肯定行得通。看起来匿名函数无法访问之前定义的map函数。map
函数的作用域是否与您在问题中发布的相同?实际上,map看起来是这样的:函数map(n){if(this.src==n){emit(this.src,this.dst);}}注意,决定传递给map的内容是由mapReduce为您完成的。还是每次都要显式地传递2
?2将是一个变量,因此它可以是任何数字这不会返回值…我得到错误reference error:map未定义。但是如果我发出两个字段,有什么变化吗?@box没有使用map
函数的返回值,重要的是通过emit
发出什么。您可以根据需要发射任意多个字段,但发射的对象的形状必须与reduce
函数返回的值相匹配(该函数目前没有)。我不太明白您的意思,您能举个例子吗?Please@box请参阅更新的答案,该答案修复了参考错误:map
问题。