[英]Generate Stats using Aggregation MongoDB
我是 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%
}, ...
我正在嘗試,但無法做到正確
首先使用$dateToParts
運算符將日期解構為其組成部分。
在基於月份和年份的那個組之后,累積所有present
、 startLate
和leaveEarly
以及計數。
分組后投影必填字段並計算百分比。
這是下面的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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.