如何计算MongoDB中日期字段上的文档数量

时间:2013-06-06 11:03:45

标签: mongodb mongodb-query aggregation-framework

场景:请注意,我在MongoDB中有以下集合:

{
    "_id" : "CustomeID_3723",    
    "IsActive" : "Y",
    "CreatedDateTime" : "2013-06-06T14:35:00Z"
}

现在我想知道特定日期创建文件的数量(比如2013-03-04) 所以,我试图使用聚合框架找到解决方案。

信息: 到目前为止,我已经构建了以下查询:

    collection.aggregate([
        { $group: {
            _id: '$CreatedDateTime'
            }
        },
        { $group: {
            count: {  _id: null, $sum: 1 }
            }
        },
        { $project: {
            _id: 0,
            "count" :"$count"
            }
        }
    ])

问题:现在考虑上面的查询,它给我计数。但不仅仅基于日期!它花费时间考虑到独特的数量。

问题:考虑到该字段有ISO日期,任何人都可以告诉我如何根据日期(即排除时间)来计算文件吗?

1 个答案:

答案 0 :(得分:6)

替换你的两组
{$project:{day:{$dayOfMonth:'$createdDateTime'},month:{$month:'$createdDateTime'},year:{$year:'$createdDateTime'}}},
{$group:{_id:{day:'$day',month:'$month',year:'$year'}, count: {$sum:1}}}

您可以在此处详细了解日期运算符:http://docs.mongodb.org/manual/reference/aggregation/#date-operators

相关问题