Mongodb Map / Reduce - Multiple Group By

时间:2012-05-01 19:35:59

标签: mongodb mapreduce mongodb-query

我正在尝试在map/reduce中运行mongodb函数,其中我将3个不同的字段分组到我的集合中的对象中。我可以运行map / reduce函数,但所有发出的字段在输出集合中一起运行。我不确定这是否正常,但输出数据进行分析需要更多的工作来清理。有没有办法将它们分开,然后使用mongoexport

让我告诉你我的意思:

我要分组的字段是日期,用户ID(或uid)和目标。

我运行这些功能:

map = function() {
    day = (this.created_at.getFullYear() + "-" + (this.created_at.getMonth()+1) + "-" + this.created_at.getDate());
    emit({day: day, uid: this.uid, destination: this.destination}, {count:1});
}

/* Reduce Function */
reduce = function(key, values) { 
    var count = 0;
    values.forEach(function(v) {
        count += v['count'];
}
);
  return {count: count};
}

/* Output Function */
db.events.mapReduce(map, reduce, {query: {destination: {$ne:null}}, out: "TMP"});

输出如下:

{ "_id" : { "day" : "2012-4-9", "uid" : "1234456", "destination" : "Home" }, "value" : { "count" : 1 } }
{ "_id" : { "day" : "2012-4-9", "uid" : "2345678", "destination" : "Home" }, "value" : { "count" : 1 } }
{ "_id" : { "day" : "2012-4-9", "uid" : "3456789", "destination" : "Login" }, "value" : { "count" : 1 } }
{ "_id" : { "day" : "2012-4-9", "uid" : "4567890", "destination" : "Contact" }, "value" : { "count" : 1 } }
{ "_id" : { "day" : "2012-4-9", "uid" : "5678901", "destination" : "Help" }, "value" : { "count" : 1 } }

当我尝试使用mongoexport时,我无法按列分隔日,uid或目标,因为地图将字段组合在一起。

我希望拥有的内容如下:

{ { "day" : "2012-4-9" }, { "uid" : "1234456" }, { "destination" : "Home"}, { "count" : 1 } }

这甚至可能吗?

顺便说一句 - 我可以通过将sed应用于文件并清理CSV来使输出正常工作。更多的工作,但它的工作。如果我能以正确的格式从mongodb中取出它,那将是理想的选择。

1 个答案:

答案 0 :(得分:1)

MapReduce仅返回{_id:some_id, value:some_value}

形式的文档

请参阅:How to change the structure of MongoDB's map-reduce results?

相关问题