- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
我正在尝试按天汇总我的数据,以便将其呈现在图表中。通过按$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/
我有一些数据代表许多不同站点的及时结果。我想找到我的结果的四分位分解以及每个站点的最大和最小日期。 找到其中的每一个都非常容易: #quartiles q = df.groupby(['site_id
我正在R中进行经典的拆分应用重组操作。随着时间的推移,我的数据集是一堆公司。我正在做的应用程序是对每个公司进行回归并返回残差,因此,我未按公司进行汇总。 plyr对此非常有用,但是当公司数量很大时,它
我正在尝试按天汇总我的数据,以便将其呈现在图表中。通过按$year、$month 和$dayOfMonth 分组,我成功地做到了这一点。但是,这意味着我的日期现在在最终结果中分为三个部分。有没有办法将
我想根据特定列“ContactID”对该 DataFrame 进行分组,但如果该组的列“PaymentType”不包含特定值,那么我想从 DataFrame 中删除整个组。 我有这样的东西: Uniq
我是一名优秀的程序员,十分优秀!