How to use variables in MongoDB Map-reduce map function

前端 未结 2 670
盖世英雄少女心
盖世英雄少女心 2020-12-05 18:37

Given a document

{_id:110000, groupings:{A:\'AV\',B:\'BV\',C:\'CV\',D:\'DV\'},coin:{old:10,new:12}}

My specs call for the specification of

相关标签:
2条回答
  • 2020-12-05 19:18

    You can pass global, read-only data into map-reduce functions using the "scope" parameter on the map-reduce command. It's not very well documented, I'm afraid.

    0 讨论(0)
  • 2020-12-05 19:37

    As pointed out by @Dave Griffith, you can use the scope parameter of the mapReduce function.

    I struggled a bit to figure out how to properly pass it to the function because, as pointed out by others, the documentation is not very detailed. Finally, I realised that mapReduce is expecting 3 params:

    • 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 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
             }
        }
    );
    
    0 讨论(0)
提交回复
热议问题