Wie von @Dave Griffith hervorgehoben, können Sie den scope verwenden Parameter von mapReduce Funktion.
Ich hatte ein bisschen Mühe, herauszufinden, wie ich es richtig an die Funktion übergeben kann, da die Dokumentation, wie von anderen erwähnt, nicht sehr detailliert ist. Schließlich erkannte ich, dass mapReduce erwartet 3 Parameter:
- Map-Funktion
- Reduzierfunktion
- Objekt mit einem oder mehreren der im Dokument definierten Parameter
Schließlich kam ich zu folgendem 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 result;
}
db.something.mapReduce(
m,
r,
{
out: {inline: 1},
// I use the scope param to pass in my variables and functions
scope: {
KEYS: KEYS,
sumValues: sumValues // of course, you can pass function objects too
}
}
);