我怎样才能将map-reduce与MongoDB和JS一起使用来获得这个



我是JS的新手,所以我在缺乏知识的情况下使用mongodb的mapreduce遇到了一些大问题,我有一个名为dailyAlerts的集合:

{
        "_id" : 25,
        "title" : "Other… Title Test Polygon 2",
        "alertDescription" : "Other… Description Test Polygon 2",
        "alertDateTime" : 1507784400100,
        "alertLatitude" : 20.5774756,
        "alertLongitude" : -103.3795262,
        "alertType" : 9,
        "userName" : "Azgad",
        "photoLink" : "www.google.com",
        "videoLink" : "www.google.com",
        "__v" : 0
}{
        "_id" : 26,
        "title" : "Other… Title Test Polygon 4",
        "alertDescription" : "Other… Description Test Polygon 4",
        "alertDateTime" : 1507784400100,
        "alertLatitude" : 20.5774756,
        "alertLongitude" : -103.3795262,
        "alertType" : 5,
        "userName" : "Azgad",
        "photoLink" : "www.google.com",
        "videoLink" : "www.google.com",
        "__v" : 0
}   
{
        "_id" : 27,
        "title" : "Other… Title Test Polygon 6",
        "alertDescription" : "Other… Description Test Polygon 6",
        "alertDateTime" : 1507784400500,
        "alertLatitude" : 20.5774756,
        "alertLongitude" : -103.3795262,
        "alertType" : 1,
        "userName" : "Azgad",
        "photoLink" : "www.google.com",
        "videoLink" : "www.google.com",
        "__v" : 0
}

这里的重要字段是"alertType",我想使用 map reduce 根据 alertType 给我所有警报的计数(可用值为 1-9),如果没有找到该 alertType 的文档,则输入 0,我还需要向我显示处理的所有文档的总数以将它们插入另一个集合中, 像这样:

{
        "_id" : 4,
        "dateRecord" : 3500,
        "type1Count" : 0,
        "type2Count" : 10,
        "type3Count" : 20,
        "type4Count" : 30,
        "type5Count" : 0,
        "type6Count" : 50,
        "type7Count" : 60,
        "type8Count" : 70,
        "type9Count" : 80,
        "totalCount" : 320,
} 

我非常感谢您对此的帮助。

我假设您的问题不是关于所需输出中的前两个属性值。可以使用如下reduce收集计数:

var data = [{ "alertType" : 9 }, { "alertType" : 5 }, { "alertType" : 1 }];
var counts = data.reduce ( (counts, obj) => {
    counts[obj.alertType]++;
    return counts;
}, Array(10).fill(0) );
console.log(counts);
.as-console-wrapper { max-height: 100% !important; top: 0; }

这将返回一个数组,在索引 k 处,您将找到alertType = k 的出现次数。由于数组也有索引 0,因此第一个值将始终为 0。当然,您可以将其转换为非数组对象或任何其他数据结构。

最新更新