簡體   English   中英

MongoDB Nodejs中唯一鍵的聚合響應格式

[英]MongoDB Aggregation response format to unique key in Nodejs

我從 mongoDB 聚合查詢得到響應,它是分組數據和動態的 select 字段,它位於“projectionObj”object:

這是我的 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]},
     ]
 }

首先,我在數組上運行了flatMap並得到了一個包含單個項目的數組。 然后運行reduce以根據名稱對series進行分組並將日期添加到categories中。
但現在系列是 object。根據需要將其轉換為數組我在最終結果中覆蓋series以使用Object.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; }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM