如何使用mongodb mapreduce计算简单移动平均线?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何使用mongodb mapreduce计算简单移动平均线?相关的知识,希望对你有一定的参考价值。

我在mongodb集合中将时间序列数据作为以下格式:

{
    "Name" : "AKBNK",
    "Date" : ISODate("2009-01-02T00:00:00Z"),
    "Close" : 3.256746559,
}

我想用mongodb mapreduce计算简单移动平均线。我试着按照以下方式执行窗口滑动,但是当周期很大时它会缓慢运行。

var mapper = function() {
    var i = 0, j = counter;
    if (j < period) {
        j = period;
        i = period - counter;
    }
    for (; i < period && j <= limit; i++, j++) {
        emit (j, this.Close);
    }

    counter++;
}

var reducer = function(key, values) {
    return Array.sum(values);
}

var finalizer = function(key, reducedValue) {
    return reducedValue / period;
}

var period = 730;

db.data.mapReduce(mapper, reducer, {finalize: finalizer, out: "smaOut", query: {Name: "AKBNK"}, sort: {Date: -1}, limit: period * 2 - 1, scope: {counter: 1, period: period, limit: period * 2 - 1}});

有什么建议我怎么能更快地做到这一点?我该如何映射数据?

答案

您可以尝试使用下面的聚合管道,它似乎可以快速浏览产生正确的结果,但速度要快得多:

db.data.aggregate({
    $match: {
        "Name": "AKBNK" // this stage will use and index if you have one on the "Name" field
    }
}, {
    $sort: { "Date": -1 }, // this stage will also use and index if you have one on "Date"
}, {
    $group: {
        "_id": null, // create one single document
        "allCloseValues": { $push: "$Close" } // that shall contain an array with all "Close" values
    }
}, {
    $addFields: {
        "copyOfAllCloseValues": "$allCloseValues" // duplicate the array
    }
}, {
    $unwind: {
        "path": "$copyOfAllCloseValues", // flatten the created single document
        "includeArrayIndex": "_id" // use the "_id" field to hold the array index
    }
}, {
    $project: {
        avg: {
            $avg: { // calculate the average of some part of the array "Close"
                $slice: [ "$allCloseValues", "$_id", 730 ] // which shall start at index "_id" and take up to 730 values
            }
        } 
    }
}, {
    $out: "smaOut" // write the resulting documents out to the "smaOut" collection
});

以上是关于如何使用mongodb mapreduce计算简单移动平均线?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 mongoose/mongodb 查询子文档中使用 mapreduce?

如何在 mongoose/mongodb 查询子文档中使用 mapreduce?

用mongodb的mapreduce可以加两个条件吗

MongoDB Map Reduce

mongodb mapReduce

MongoDB 聚合操作