我有一个具有以下架构的数据集:
Schema({
'ID': {type:Number},
'Date': {type:Date},
'DrivingHours':{type:Number}
})
并且我想通过归纳为以下结果来达成共识:
[
{
"DrivingHours": [
{
"9": 2.6061111111111113,
"36": 0,
"54": 0.016944444444444446,
"Date": "2019-9-1"
},
{
"9": 0.5738888888888889,
"36": 0,
"54": 0,
"Date": "2019-9-2"
},
...
因为密钥是我的车辆的ID。遵循以下原则,我已接近目标,但无法整合“日期”。有没有技巧在使用'$ replaceRoot'之后添加此参数?
{$facet: {
DrivingHours: [
{$group: {_id: {Date: '$Date', ID: '$ID'},
ID: {$first: '$ID'},
DrivingHours: {$first: '$DrivingHours'}
}},
{$group: {_id: '$_id.Date',
arrDrivingHours: {
$push: {'k': { $toString: '$ID' }, 'v':{ $ifNull: [ '$DrivingHours', 0 ] }}
}}},
{'$replaceRoot':{
newRoot: {$arrayToObject:'$arrDrivingHours'}
}
}
]
}}
我正在使用构面,因为稍后我想添加数据集的其他方面,但是效果很好。
答案 0 :(得分:0)
我只需要在“ $ mergeObjects”中添加日期对象。因此,解决方案是:
{$facet: {
DrivingHours: [
{$group: {_id: {Date: '$Date', ID: '$ID'},
ID: {$first: '$ID'},
DrivingHours: {$first: '$DrivingHours'}
}},
{$group: {_id: '$_id.Date',
arrDrivingHours: {
$push: {'k': { $toString: '$ID' }, 'v':{ $ifNull: [ '$DrivingHours', 0 ] }}
}}},
{'$replaceRoot':{
newRoot: {"$mergeObjects": [
{"Date": "$_id.Date"},
{$arrayToObject: "$ObjDrivingHours"}
]
}
}
}
]
}
}