gpt4 book ai didi

mongodb - 如何统计MongoDB中日期字段的文档数量

转载 作者:行者123 更新时间:2023-12-03 01:04:59 26 4
gpt4 key购买 nike

场景:考虑一下,我在 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 日期,谁能告诉我如何仅基于日期(即排除时间)来统计文档?

最佳答案

将两个组替换为

{$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

关于mongodb - 如何统计MongoDB中日期字段的文档数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16960478/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com