按日期分组几个变量

时间:2014-12-29 08:58:37

标签: node.js mongodb mapreduce mongodb-query aggregation-framework

mongodb项目中通过mongoose使用node.js。 我的文件有以下结构:

{ created: new Date("2014-12-24"), last_visited: new Date("2014-12-24") },
{ created: new Date("2014-12-16"), last_visited: new Date("2014-12-24") },
{ created: new Date("2014-12-13"), last_visited: new Date("2014-12-13") },
{ created: new Date("2014-12-12"), last_visited: new Date("2014-12-20") },
{ created: new Date("2010-01-01"), last_visited: new Date("2014-12-20") }

我想显示在过去30天内某个日期创建/更新了多少文档。所以输出应该是:

{ date: ISODate("2014-12-12"), created: 2, last_visited: 0 },
{ date: ISODate("2014-12-13"), created: 1, last_visited: 0 },
{ date: ISODate("2014-12-16"), created: 1, last_visited: 0 },
{ date: ISODate("2014-12-20"), created: 0, last_visited: 2 },
{ date: ISODate("2014-12-22"), created: 0, last_visited: 1 },
{ date: ISODate("2014-12-24"), created: 0, last_visited: 2 },

请注意,由于年龄超过30天,因此跳过了2010年的条目。

我该怎么做?

2 个答案:

答案 0 :(得分:1)

地图减少问题:

var old = new Date();
old.setDate(old.getDate()-30);

var filter = { created : {$gt : old}, last_visited : {$gt : old} };

var map = function()
{        
    emit(this.created, {created : 1, last_visited : 0 });      
    emit(this.last_visited, {created : 0, last_visited : 1 });    
}

var reduce = function(key, values)
{
    var out = {created : 0, last_visited : 0 };

    for(i in values)
    {
        var value  = values[i];
        if(value.created != 0)
        {
            out.created++;
        }
        else
        {
            out.last_visited++;
        }
    }

    return out;
}

db.runCommand(
               {
                 mapReduce: "test2",
                 map: map,
                 reduce: reduce,                
                 out: { "inline": 1 },
                 query: filter
               }
             ).results

答案 1 :(得分:1)

试试这个

db.users.aggregate([
    {$group: {
            "_id": {
                month: {$month: "$created"},
                day: {$dayOfMonth: "$created"},
                year: {$year: "$created"},
            },
            date: {$max: '$created'},
            created: {$sum: 1},
            last_visited: {$sum: 1},
        }},
        {$sort: {
            'date': -1
        }}
])

由于