【问题标题】:Generate Stats using Aggregation MongoDB使用聚合 MongoDB 生成统计信息
【发布时间】:2020-08-18 10:02:10
【问题描述】:

我是 MongoDB 聚合的新手。

我正在使用一个小型 Web 应用程序来存储每天的出勤率,并根据月份和年份进行报告。

这是DB上的出勤集合:

{
        _id : 5f3b7f85a189d04eec4ec2e8
        dated :2020-03-18T12:01:25.348+00:00
        empId:"10013"
        employee:5f2b66620ec17b4b1034549a
        weekOff:false
        inTime:2020-08-18T12:01:34.308+00:00
        outTime:2020-08-18T12:10:34.308+00:00
        present:true
        startLate:true
        leaveEarly:true
} ........

我如何获得这样的统计数据:

{
    month : 01,
    year : 2020,
    present : 75 %
    absent : 25%
    startLate : 10%
    leaveEarly: 25%
},
{
    month : 02,
    year : 2020,
    present : 80 %
    absent : 22%
    startLate : 20%
    leaveEarly: 05%
}, ...

我在尝试,但无法做到正确

【问题讨论】:

  • 你有什么尝试吗?
  • 其实我对此很陌生,只是想弄清楚。

标签: javascript mongodb mongodb-query aggregation-framework


【解决方案1】:

首先使用$dateToParts 运算符将日期解构为其组成部分。

在该组之后基于月份和年份,累积所有presentstartLateleaveEarly 以及计数。

分组后,投影必填字段并计算百分比。

这是下面的fiddle

var pipeline = [
  {
    $addFields: {
      date: {
        $dateToParts: {
          date: "$dated"
        }
      }
    }
  },
  {
    $group: {
      _id: {
        month: "$date.month",
        year: "$date.year"
      },
      sum: {
        $sum: 1
      },
      present: {
          $sum: {
            $cond: {
              if: { $eq: ['$present', true] },
              then: 1,
              else: 0
            }
          }
      },
      absent: {
          $sum: {
            $cond: {
              if: { $eq: ['$present', false] },
              then: 1,
              else: 0
            }
          }
      },
      startLate: {
          $sum: {
            $cond: {
              if: { $eq: ['$startLate', true] },
              then: 1,
              else: 0
            }
          }
       },
       leaveEarly: {
          $sum: {
            $cond: {
              if: { $eq: ['$leaveEarly', true] },
              then: 1,
              else: 0
            }
          }
       }
    }
  },
  {
    $project: {
        month: '$id.month',
        year: '$id.year',
        "present": {
            $multiply: [
                { $divide: ["$present", "$sum"] },
                100
            ]
        },
        "absent": {
            $multiply: [
                { $divide: ["$absent", "$sum"] },
                100
            ]
        },
        "startLate": {
            $multiply: [
                { $divide: ["$startLate", "$sum"] },
                100
            ]
        },
        "leaveEarly": {
            $multiply: [
                { $divide: ["$leaveEarly", "$sum"] },
                100
            ]
        }
    }
  }
];

db.collection.aggregate(pipeline);

【讨论】:

  • 感谢@Kunal Mukherjee 高度赞赏的帮助?
猜你喜欢
  • 2023-01-12
  • 2012-10-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多