每年$ group之后如何获得所有项目的平均值?

时间:2017-12-01 21:11:17

标签: mongodb aggregation-framework aggregate

我创建了一个MongoDB聚合管道。我按照房间和年份对数据进行分组,得到以下结果。但是,我想获得每年任何房间的平均值。换句话说,我希望获得平均房间交易收入组数年。

这是我的管道:

let pipeline = [
 {
  "$group" : {
    "_id" : { "room" : "$room", "year" : "$year"},
    "total_revs" : { "$sum" : 1 },
    "average_stay" : { "$avg" : { "$subtract": ["$endDate", "$startDate"]}},
    "average_leadtime"     : { "$avg" : { "$subtract": ["$startDate", "$orderDate"]}},
    "average_party_size"   : { "$avg" : "$numberOfPeople" },
    "transaction_revenue"  : { "$avg": "$tranFee" }
  }
}  
]

let promise = HReservation.aggregate(pipeline).exec();
promise.then(result => res.send(result))
.catch(err => res.status(500).send(err));

此管道产生以下结果:

[
{
    "_id": {
        "year": 2013
    },
    "total_revs": 66100,
    "average_stay": 233698275.34039333,
    "average_leadtime": 6089703358.547655,
    "average_party_size": null,
    "transaction_revenue": 10.53087821482602
},
{
    "_id": {
        "year": 2012
    },
    "total_revs": 60936,
    "average_stay": 235630563.21386373,
    "average_leadtime": 6001076644.348168,
    "average_party_size": null,
    "transaction_revenue": 10.534949947485886
},
{
    "_id": {
        "year": 2010
    },
    "total_revs": 50492,
    "average_stay": 241539095.3022261,
    "average_leadtime": 6193156175.235681,
    "average_party_size": null,
    "transaction_revenue": 10.506802463756634
},
{
    "_id": {
        "year": 2015
    },
    "total_revs": 81832,
    "average_stay": 229180877.89617753,
    "average_leadtime": 6365565822.661061,
    "average_party_size": null,
    "transaction_revenue": 10.7106377700655
}
]

问题:

这只是告诉我每笔交易的交易成本大致是多少...... 10美元,数据略有偏差。

我需要这些平均数的总和......每年。我想我正确地说这个。

期望的结果:我希望获得每年平均的房间交易总收入。

如何达到我想要的效果?

1 个答案:

答案 0 :(得分:0)

我将我的房间ID错误地投射到我的第一个$group阶段。一旦我能够正确分组,最终的$group就是明显的答案。

                {
                    "$group" : {
                        "_id" : {"room": "$room", "year": "$year"},
                        "total_revs" : { "$sum" : 1 },
                        "average_stay"         : { "$avg" : { "$subtract": ["$endDate", "$startDate"]}},
                        "average_leadtime"     : { "$avg" : { "$subtract": ["$startDate", "$orderDate"]}},
                        "transaction_revenue"   : { "$sum" : "$tranFee" }
                    }
                },
                {
                    "$group" : {
                        "_id" : "$_id.year",
                        "average_tr" : { "$avg" : "$transaction_revenue" }
                    }
                }