2014-11-06 56 views
0

我有一个大数据集合,我试图从Mongo(节点js)中提取一些图表。Mongo聚合查询提取最后7天的数据(node.js)

我需要从几千个用户中抽取最后7天的数据。每个用户数据的特定部分的格式,像这样:

{ 
    "passedModules" : 
    [{ 
     "module" : ObjectId("53ea17dcac1d13a66fb6d14e"), 
     "date" : ISODate("2014-09-17T00:00:00.000Z") 
    }, 
    { 
     "module" : ObjectId("53ec5c91af2792f1112554e8"), 
     "date" : ISODate("2014-09-17T00:00:00.000Z") 
    }, 
    { 
     "module" : ObjectId("53ec5c5baf2792f1112554e6"), 
     "date" : ISODate("2014-09-17T00:00:00.000Z") 
    }] 
} 

目前我有工作查询的真的很乱组,但我相信这是可能与蒙戈完全做?

基本上,我需要从7天前到现在,以动态的方式提出所有条目。

以这种方式使用动态日期,更具体地说是使用mongo中的聚合框架吗?聚合框架的原因是我需要将这些事件进行分组。

非常感谢

回答

5

对于这种类型的查询的一般模式是:

// Compute the time 7 days ago to use in filtering the data 
var d = new Date(); 
d.setDate(d.getDate()-7); 

db.users.aggregate([ 
    // Only include the docs that have at least one passedModules element 
    // that passes the filter. 
    {$match: {'passedModules.date': {$gt: d}}}, 
    // Duplicate the docs, one per passedModules element 
    {$unwind: '$passedModules'}, 
    // Filter again to remove the non-matching elements 
    {$match: {'passedModules.date': {$gt: d}}} 
])