gpt4 book ai didi

MongoDB 聚合 : How do I recombine a date using $project?

转载 作者:IT老高 更新时间:2023-10-28 13:14:59 26 4
gpt4 key购买 nike

我正在尝试按天汇总我的数据,以便将其呈现在图表中。通过按$year$month$dayOfMonth 分组,我成功地做到了这一点。但是,这意味着我的日期现在在最终结果中分为三个部分。有没有办法将三个数字连接回日期格式,或者有没有另一种方法可以按天分组而不拆分日期?下面是我所拥有的一个工作示例:

Sentiment.aggregate([
{
$match: { 'content.term' : term_id }
}, {
$group: {
_id: {
year : { $year : '$created_at' },
month : { $month : '$created_at' },
dayOfMonth : { $dayOfMonth : '$created_at' },
},
sum : { $sum : '$score'},
count : { $sum : 1 }
},
}, {
$project: {
_id : 0,
date : '$_id',
sum : 1,
count : 1,
avg : { $divide: ['$sum', '$count'] }
}
}
], function(err, result){
if(err) callback(err);
else callback(null, result);
});

这是一个示例结果:

[
{
"sum": 201,
"count": 3,
"date": {
"year": 2013,
"month": 7,
"dayOfMonth": 5
},
"avg": 67
},
{
"sum": 186,
"count": 6,
"date": {
"year": 2013,
"month": 7,
"dayOfMonth": 8
},
"avg": 31
},
{
"sum": 834,
"count": 9,
"date": {
"year": 2013,
"month": 7,
"dayOfMonth": 9
},
"avg": 92.66666666666667
}
]

理想情况下,我希望 date 是一个有效日期,这样我以后就不必再转换它了。我试过使用 $concat 但这仅适用于字符串。我正在使用 Mongoose 如果这有所作为。

最佳答案

假设,当您按年、月和日对文档进行分组时,小时和分钟是无用的,您可以使用其中一个运算符来获取日期样本:$first, $last$min$max

Sentiment.aggregate([
{
$match: { 'content.term' : term_id }
}, {
$group: {
_id: {
year : { $year : '$created_at' },
month : { $month : '$created_at' },
dayOfMonth : { $dayOfMonth : '$created_at' },
},
dt_sample : { $first : '$created_at' },
sum : { $sum : '$score'},
count : { $sum : 1 }
},
}, {
$project: {
_id : 0,
date : '$dt_sample',
sum : 1,
count : 1,
avg : { $divide: ['$sum', '$count'] }
}
}
], function(err, result){
if(err) callback(err);
else callback(null, result);
});

您将拥有一个包含任意小时、分钟和秒的日期字段。

关于MongoDB 聚合 : How do I recombine a date using $project?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17598826/

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