将范围添加到$ group aggregate

时间:2015-05-17 03:49:20

标签: mongodb

所以,我有这个找到在某一天创建的项目,结果很好。我想要的是将其限制在过去7天内的结果。我怎么能这样做?

db.leaderboard.aggregate({
    $group: {
        _id: {
            year: {$year: "$created"}, 
            month: {$month: "$created"}, 
            day: {$dayOfMonth: "$created"}
        }, 
        count: {"$sum": 1}
    }
})

我有这个,它使用find,但我无法弄清楚如何将其与aggregate合并。

{
    created: {
        $gt: new Date((new Date()) - (1000 * 60 * 60 * 24 * 7))
    }
}

我尝试将其放在群组之后,我收到此错误:exception: A pipeline stage specification object must contain exactly one field

我尝试在count之后放置它并收到此错误:exception: the group aggregate field name '$gt' cannot be an operator name

我可以做些什么来让这两者一起工作?

1 个答案:

答案 0 :(得分:0)

您需要在汇总

中添加$ match阶段
 db.leaderboard.aggregate([
    { $match: { created: { $gt: new Date((new Date()) - (1000 * 60 * 60 * 24 * 7))}}},
     { $group: {
        _id: {
            year: {$year: "$created"}, 
            month: {$month: "$created"}, 
            day: {$dayOfMonth: "$created"}
        }, 
        count: {"$sum": 1}
     }}
    ])