[英]Mongo DB (node js) group by dates and sum values of unique ids
I have the following documents in my collection: 我的收藏中有以下文件:
{
"_id": ObjectId("5b8fed64b77d7829788ebdc8"),
"valueId": "6e01c881-c15e-b754-43bd-0fe7381cc02a",
"value": 14,
"date": "2018-09-05T14:51:11.427Z"
}
I want to group the "date" by a certain interval, get for all "valueId" a sum of the "value", which is inside the date interval. 我想按一定的时间间隔对“日期”进行分组,为所有“ valueId”获取“值”的总和,这是在日期间隔内。 My current aggregation looks like this: 我当前的汇总如下所示:
myCollection.aggregate([
{
$match: {
date: {
$gte: start,
$lte: end,
},
},
},
{
$group: {
_id: {
$toDate: {
$subtract: [{ $toLong: '$date' }, { $mod: [{ $toLong: '$date' }, interval] }],
},
},
valueId: { $addToSet: '$valueId' },
},
},
{
$project: {
_id: 1,
valueId: 1,
},
},
]);
Which gives out something like this: 给出了这样的内容:
{
_id: 2018-09-04T15:45:00.000Z,
valueId:[
'cb255343-9c16-f495-9c29-3697d6c7d6cb',
'97e729aa-7b0f-c107-d591-01188b768a7a'
]
}
How can I get it to something like this (simplified with one value): 我怎样才能得到这样的东西(用一个值简化):
{
_id: 2018-09-04T15:45:00.000Z,
valueId: [[
'cb255343-9c16-f495-9c29-3697d6c7d6cb',
<sum of value>
]]
}
EDIT: Endsolution: 编辑:最终解决方案:
myCollection.aggregate([
{"$match":{"date":{"$gte":start,"$lte":end}}},
{"$group":{
"_id":{
"interval":{"$toDate":{"$subtract":[{"$toLong":"$date"},{"$mod":[{"$toLong":"$date"},interval]}]}},
"valueId":"$valueId"
},
"value":{"$sum":"$value"}
}},
{ $group: {
_id: "$_id.interval",
values: {
$addToSet: { id: "$_id.valueId", sum: "$value" },}
}}])
You can use multiple group, one for summing value for each valueid and interval combination and second group to push all the documents for interval. 您可以使用多个组,一组用于每个valueid和间隔组合的值求和,第二组用于将所有文档推入间隔。
myCollection.aggregate([
{"$match":{"date":{"$gte":start,"$lte":end}}},
{"$group":{
"_id":{
"interval":{"$toDate":{"$subtract":[{"$toLong":"$date"},{"$mod":[{"$toLong":"$date"},interval]}]}},
"valueId":"$valueId"
},
"value":{"$sum":"$value"}
}},
{"$group":{
"_id":"$_id.interval",
"valueId":{"$push":{"id":"$_id.valueId","sum":"$value"}}
}}
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.