繁体   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