如何使用芒果聚合输出另一种模式

时间:2018-03-23 06:06:05

标签: javascript node.js mongodb aggregation-framework mongoose-schema

你好我的问题是如何从数据库获取最近四个月的记录。我得到了输出但没有得到我预期的模式所以如何做到这一点可以帮助我解决这个问题。

db.Air_pollution.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"}
    }
},
{
    $sort:{"year":-1}
},
{
    $project:{
        year:'$_id.year',
        avgofozone:'$avgofozone',
        month:'$_id.month',_id:0
    }
}
]) 

输出是:

{ "avgofozone" : 21.07777777777778, "year" : 2018, "month" : 2 }
{ "avgofozone" : 17.8, "year" : 2018, "month" : 3 }
{ "avgofozone" : 17.8, "year" : 2018, "month" : 1 }

预期产出:

zone_type       year        january   febravary           march
avgofozone     2018         17.8      21.07777           17.8 

1 个答案:

答案 0 :(得分:1)

您已经拥有了所需的数据,而不是试图从MongoDB中获取您需要的数据,为什么不在应用层中对其进行格式化呢?

一些简单的JavaScript可以做到这一点:

const months = [
  'January', 'February', 'March', 'April', 'May',
  'June', 'July', 'August', 'September',
  'October', 'November', 'December'
];

function monthNumToName(monthnum) {
  return months[monthnum - 1];
}

const results = [{
  "avgofozone": 21.07777777777778,
  "year": 2018,
  "month": 2
}, {
  "avgofozone": 17.8,
  "year": 2018,
  "month": 3
}, {
  "avgofozone": 17.8,
  "year": 2018,
  "month": 1
}];

const statsByYear = results.reduce((a, c) => {
  const {
    year,
    month,
    avgofozone
  } = c;
  if (!a[year])
    a[year] = {
      zone_type: 'avgofozone',
      year,
      [monthNumToName(month)]: avgofozone
    }
  else a[year][monthNumToName(month)] = avgofozone
  return a;
}, {});
const formatted = Object.keys(statsByYear).map(k => {
  return statsByYear[k];
});

console.log(formatted);