Mongo嵌套$ group计算年份和月份

时间:2019-04-18 11:14:36

标签: mongodb mongodb-query aggregation-framework

这是我所拥有的示例订购文件

{startDate: “2010:10:10”, numberOfHours: 10},
{startDate: “2010:11:10”, numberOfHours: 5},
{startDate: “2011:12:10”, numberOfHours: 1},
{startDate: “2012:10:10”, numberOfHours: 10}

首先,我要计算 startDate 每年的订单数量(totalOrders)并计算numberOfHours(totalHours)之和。然后,对于一年中的每个月,我需要计算订单数(订单)并计算numberOfHours(小时)的总和。输出应如下所示

    [
    // Current year first
   {
     year: 2019,
     totalOrders: 120,
     totalHours: 1234,
     months: [
       { 
          month: 0, // 0 based month index so jan = 0
          orders: 12, 
          hours: 120 
      },
{ 
          month: 1, 
          orders: 5, 
          hours: 100 
      }
      ////////////
      ]
    },
// 2018 etc
]

我查看了嵌套的@group示例,但找不到匹配项。我知道如何按年和月分组

const result = await this._collection.aggregate([
            {
                $project: {
                    startYear: { $substr: ["$startDate", 0, 4] },
                    startMonth: { $substr: ["$startDate", 5, 2] }
                }
            },
            {
                $group: {
                    _id: { year: "$startYear", month: "$startMonth" },
                    orders: { $sum: 1 },
                    hours: { $sum: "$numberOfHours" }
                },
            },
        ]).toArray();

任何想法如何进行我提到的输出? 任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:3)

基本上,您需要再添加$group,然后每年将$push个月份添加到数组中:

const result = await this._collection.aggregate([
    {
        $project: {
            startYear: { $substr: ["$startDate", 0, 4] },
            startMonth: { $substr: ["$startDate", 5, 2] }
        }
    },
    {
        $group: {
            _id: { year: "$startYear", month: "$startMonth" },
            orders: { $sum: 1 },
            hours: { $sum: "$numberOfHours" }
        },
     },
     {
         $group: {
             _id: { year: "$_id.year" },
             totalOrders: { $sum: "$orders" },
             totalHours: { $sum: "$hours" },
             months: {
               $push: {
                 month: "$_id.month",
                 orders: "$orders",
                 hours: "$hours"
               }
             }
         }
     }
]).toArray();

答案 1 :(得分:1)

您可以更好地使用$dateFromString运算符,并可以$group使用任意格式。

db.collection.aggregate([
  { "$group": {
    "_id": {
      "month": { "$month": { "$dateFromString": { "dateString": "$startDate", "format": "%Y:%m:%d" }}},
      "year": { "$year": { "$dateFromString": { "dateString": "$startDate", "format": "%Y:%m:%d" }}}
    },
    "hours": { "$sum": "$numberOfHours" },
    "count": { "$sum": 1 }
  }},
  { "$group": {
    "_id": "$_id.year",
    "totalHours": { "$sum": "$hours" },
    "totalOrders": { "$sum": "$count" },
    "months": {
      "$push": {
        "month": "$_id.month",
        "order": "$count",
        "hours": "$hours"
      }
    }
  }}
])