我從 mongoDB 聚合查詢中得到回應,該查詢是分組資料并動態選擇“projectionObj”物件上的欄位:
這是我的 mongodb聚合查詢:
let projectionObj = {
"date": 1,
"height": 1,
"bmi": 1,
"level": 1,
}
UpdateForm.aggregate([
{ $match: {
"id": id,
"date": {
"$gte": startdate,
"$lte": enddate,
}}},
{ $group: {
_id: {
year: { $year: "$date" },
month: { $month: "$date" },
day: { $dayOfMonth: "$date" },
},
items: {
$push: '$$ROOT',
}}},
{$project: {
"_id": 0,
"items": projectionObj
}},
])
以下是聚合結果:
[
{
items: [{
date: "2022-03-11",
height: '1',
bmi: '1',
level: '1'
},
{
date: "2022-03-11",
height: '2',
bmi: '2',
level: '2'
}]
},
{
items: [{
date: "2022-03-08",
height: '3',
bmi: '3',
level: '3'
}]
}
]
我想將聚合結果格式化為所需的格式,如下所示
{
categories: ["2022-03-11", "2022-03-11", "2022-03-08"],
series: [
{name: "height", data: [1,2,3]},
{name: "bmi", data: [1,2,3]},
{name: "level", data: [1,2,3]},
]
}
uj5u.com熱心網友回復:
首先,我flatMap在陣列上運行并獲得了一系列單獨的專案。然后運行根據名稱對reduce進行分組并將日期添加到.
但現在系列是一個物件。根據需要將其轉換為陣列我在最終結果中覆寫以使用分組值陣列seriescategoriesseriesObject.values
let a = [
{
items: [{
date: "2022-03-11",
height: '1',
bmi: '1',
level: '1'
},
{
date: "2022-03-11",
height: '2',
bmi: '2',
level: '2'
}]
},
{
items: [{
date: "2022-03-08",
height: '3',
bmi: '3',
level: '3'
}]
}
]
let res = a.flatMap(el => el.items).reduce((acc,{date,...curr})=>{
acc.categories.push(date)
Object.entries(curr).forEach(([k,v])=>{
if(!acc.series[k])acc.series[k]={name:k,data:[]}
acc.series[k].data.push(parseInt(v))
})
return acc;
},{categories:[],series:{}})
res = {...res,series:Object.values(res.series)}
console.log(res)
.as-console-wrapper { max-height: 100% !important; top: 0; }
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/440279.html
標籤:javascript 节点.js 反应 mongodb 猫鼬
上一篇:動態Mongoose欄位型別
