我可以让Mongo map减少计算对象的多个值吗?

时间:2018-03-02 00:41:03

标签: javascript mongodb mapreduce

我有一个我想要映射的集合,按ID和日期缩小,以生成商店和在线销售产品的图表。为每个事务创建一个新对象,因此我希望将它们减少到给定日期的总计数。对象看起来像这样:

object
{
      "ProductID": 1
      "Purchase Method": In Store
      "Date": 2018-01-16
      "Count": 5
}

我想要实现的输出是将商店和在线购买合并为一个对象,其中一个键是id和日期,然后值是每个方法的计数,如下所示:

ProductID: 1
Date: 2018-01-16
[
    {Name: "In store", Count: 3}
    {Name: "Online", Count: 2}
]

我当前的方法是通过Id,date和Purchase Method映射对象,因此reduce将使用该方法获取该日期该id的总计数,但这会导致id和date有两个条目, 1个用于商店,1个用于在线。这是我职能的当前状态:

var mapDailySales = function() {
var sale = this;

/*Converts timestamp to just date */
var pad = function pad(n, width, z) {
z = z || '0';
n = n + '';
return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
};

var d = sale.Date;
var date = d.getFullYear() + "-" + pad(d.getMonth() + 1, 2, 0) + "-" + pad(d.getDate(), 2, 0);

emit({ProductId: sale.ProductID, Date:date, Method: sale.PurchaseMethod},
{Name: sale.PurchaseMethod, Count: 1})
};


var reduceDailySales = function(key, value) {
var res = {Name: 0, Count: 0};

value.forEach(function(value){
res.Name = value.Name;
res.Count += value.Count;
});

return res; 
};

Current Output看起来像这样:

{
    "_id" : {
        "ProductId" : 1,
        "Date" : "2018-01-16",
        "Method" : "Online"
    },
    "value" : {
        "Name" : "Online",
        "Count" : 3
    }
}

有没有办法实现我想要的输出而不会在当前输出上再次减少地图?

1 个答案:

答案 0 :(得分:1)

您可以使用聚合管道来获取结果,而不是mapReduce,$group按产品ID和日期,$project您可以将计数映射到数组

添加$out将结果写入新集合,删除它将返回游标

db.prod.aggregate([
    {$group : {
        _id : {ProductID : "$ProductID", Date : "$Date"},
        onlineCount : {$sum : {$cond : [{$eq : ["$PurchaseMethod", "Online"]}, "$Count" , 0]}},
        storeCount : {$sum : {$cond : [{$eq : ["$PurchaseMethod", "In Store"]}, "$Count" , 0]}}
        }
    },
    {$project : {
        _id : 0,
        ProductID : "$_id.ProductID",
        Date : "$_id.Date",
        counts : [{Name: "In Store", Count: "$storeCount"},{Name : "Online", Count: "$onlineCount"}]
    }},
    {$out : "count_stats"}
]).pretty()

集合

> db.prod.find()
{ "_id" : ObjectId("5a98ce4a62f54862fc7cd1f5"), "ProductID" : 1, "PurchaseMethod" : "In Store", "Date" : "2018-01-16", "Count" : 5 }
{ "_id" : ObjectId("5a98ce4a62f54862fc7cd1f6"), "ProductID" : 1, "PurchaseMethod" : "Online", "Date" : "2018-01-16", "Count" : 2 }
> 

结果

> db.count_stats.find()
{ "_id" : ObjectId("5a98d3366a5f43b12a39b4ac"), "ProductID" : 1, "Date" : "2018-01-16", "counts" : [ { "Name" : "In Store", "Count" : 5 }, { "Name" : "Online", "Count" : 2 } ] }
> 

如果您想使用mapReduce,可以使用finalize来进一步缩小或转换结果

db.prod.mapReduce(
    <map>,
    <reduce>,
    {
        out: <collection>,
        finalize: <function>
    }
)