需求是根据集合col的create_date字段只查询日期年月日,然后去汇总统计。
$dateToString
根据用户指定的格式将日期对象转换为字符串。
{ $dateToString: {
date: <dateExpression>,
format: <formatString>,
timezone: <tzExpression>,
onNull: <expression>
} }
- date:转换为字符串的日期。
- format:可选的。日期格式规范。如果未指定,则$dateToString使用 "%Y-%m-%dT%H:%M:%S.%LZ"默认格式。
- timezone:运算结果的时区。
- onNull:可选的。如果date为null或缺少,则返回的值。参数可以是任何有效的表达式。如果未指定,$dateToString则如果datenull为null或缺少,则返回null 。
查询字段只截取日期年月日
查询集合col的create_date字段只截取日期年月日
db.col.aggregate(
{$project:{"_id":"$_id", "create_date":{"$dateToString":{ format:"%Y-%m-%d",date:"$create_time"}}}}
)
按年月日汇总统计
db.col.aggregate(
{$project:{"_id":"$_id", "create_date":{"$dateToString":{ format:"%Y-%m-%d",date:"$create_time"}}}},
{$group:{ "_id":"$create_date",count:{$sum:1}}}
)
// 去掉$project,直接统计
db.col.aggregate(
{$group:{ "_id":{"$dateToString":{ format:"%Y-%m-%d",date:"$create_time"}},count:{$sum:1}}}
)
如果有条件限制
db.col.aggregate({
"$match":{"create_time":{$gte:ISODate("2022-05-01T00:00:00Z"),$lte:ISODate("2022-05-05T00:00:00Z")}}
},
{$group:{ "_id":{"$dateToString":{ format:"%Y-%m-%d",date:"$create_time"}},count:{$sum:1}}}
)
相当于SQl的查询语句
SELECT DATE_FORMAT(create_time,'%Y-%m-%d') as create_date,
count(*) as `count`
FROM col
WHERE create_time >= '2022-05-01'
AND create_time <= '2022-05-05'
GROUP BY DATE_FORMAT(create_time,'%Y-%m-%d');
$year, $month, $dayOfMonth
显示年月日:年: $year 月: $month 日: $dayOfMonth
参考:https://mongodb.net.cn/manual/reference/operator/aggregation/dateToString/
这篇博客介绍了如何在MongoDB中利用聚合框架进行日期字段的处理,包括使用$dateToString将日期字段格式化为年月日,并基于此进行数据汇总统计。示例展示了如何进行无条件和有条件(时间范围)的统计,以及等效的SQL查询语句。此外,还提到了$year, $month, $dayOfMonth等日期操作符用于显示日期的年月日部分。
1318

被折叠的 条评论
为什么被折叠?



