如何通过 MongoDB 聚合得到扁平 JSON 结果?
How to get flatten JSON result with MongoDB aggregation?
聚合后,我得到了预期之外的输出。有什么我可以做的吗?
aggregate([
{ "$match": {
"CREATE_DATE": {
"$lte": new Date(),
"$gte": new Date(new Date().setDate(new
Date().getDate()-120))
}
} },
{ "$group": {
"_id": {
"month": { "$month": "$CREATE_DATE" },
"year": { "$year": "$CREATE_DATE" }
},
"avgofozone": { "$avg": "$OZONE" }
} }
])
实际输出:
[
{ "avgofozone" : 21.07777777777778, "year" : 2018, "month" : 2 }
{ "avgofozone" : 17.8, "year" : 2018, "month" : 3 }
{ "avgofozone" : 17.8, "year" : 2018, "month" : 1 }
]
预期输出:
[
{
"zone_type": "avgofozone",
"year": 2018,
"February": 21.07777777777778,
"March": 17.8,
"January": 17.8
}
]
使用 MongoDB >= v3.4.4,您可以将以下阶段添加到现有管道的末尾,这将为您进行转换:
{
$addFields: {
result: {
$let: {
vars: { "months": [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ], arr: { $objectToArray: "$$ROOT" } },
in: {
"k" : { $arrayElemAt: [ "$$months" , { $subtract: [ { $arrayElemAt: [ "$$arr.v" , 2 ] }, 1 ] } ] },
"v" : { $arrayElemAt: [ "$$arr.v" , 0 ] }
}
}
}
}
}, {
$group: {
_id: "$year",
result: { $push: "$result" },
}
}, {
$addFields: {
"result": { $arrayToObject: "$result" },
}
}, {
$addFields: {
"result.zonetype": "avgofozone",
"result.year": "$_id"
}
}, {
$replaceRoot: {
newRoot: "$result"
}
}
聚合后,我得到了预期之外的输出。有什么我可以做的吗?
aggregate([
{ "$match": {
"CREATE_DATE": {
"$lte": new Date(),
"$gte": new Date(new Date().setDate(new
Date().getDate()-120))
}
} },
{ "$group": {
"_id": {
"month": { "$month": "$CREATE_DATE" },
"year": { "$year": "$CREATE_DATE" }
},
"avgofozone": { "$avg": "$OZONE" }
} }
])
实际输出:
[ { "avgofozone" : 21.07777777777778, "year" : 2018, "month" : 2 } { "avgofozone" : 17.8, "year" : 2018, "month" : 3 } { "avgofozone" : 17.8, "year" : 2018, "month" : 1 } ]
预期输出:
[ { "zone_type": "avgofozone", "year": 2018, "February": 21.07777777777778, "March": 17.8, "January": 17.8 } ]
使用 MongoDB >= v3.4.4,您可以将以下阶段添加到现有管道的末尾,这将为您进行转换:
{
$addFields: {
result: {
$let: {
vars: { "months": [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ], arr: { $objectToArray: "$$ROOT" } },
in: {
"k" : { $arrayElemAt: [ "$$months" , { $subtract: [ { $arrayElemAt: [ "$$arr.v" , 2 ] }, 1 ] } ] },
"v" : { $arrayElemAt: [ "$$arr.v" , 0 ] }
}
}
}
}
}, {
$group: {
_id: "$year",
result: { $push: "$result" },
}
}, {
$addFields: {
"result": { $arrayToObject: "$result" },
}
}, {
$addFields: {
"result.zonetype": "avgofozone",
"result.year": "$_id"
}
}, {
$replaceRoot: {
newRoot: "$result"
}
}