按日期对多个变量进行分组



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

{ 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 },

请注意,2010 年的条目被跳过,因为它早于 30 天。

我该怎么做?

地图减少问题:

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

试试这个

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
        }}
])

谢谢

相关内容

  • 没有找到相关文章

最新更新