Ms1*_*s13 1 aggregate-functions mongodb mongodb-query aggregation-framework
我有两个日期Start Date: 2019-08-13和End Date: 2019-08-20。我想结束日期的差异在工作日(节假日除外)项的开始日期。所以我的成绩会4作为2019-08-15一个节日和2019-08-17,2019-08-18是周末。
小智 5
试试这个查询:
db.collection.aggregate([
{$addFields: {days_in_millis: { $add: [{$subtract: ["$end_date", "$start_date"]}, 86400000] } }},
{$project: {end_date: 1, start_date: 1, millis_range: {$range: [0, "$days_in_millis", 86400000 ] } } },
{$project: {dates_in_between_inclusive: {
$map: {
input: "$millis_range",
as: "millis_count",
in: {$add: ["$start_date", "$$millis_count"]}
}
}}},
{$unwind: "$dates_in_between_inclusive"},
{$project: {date: "$dates_in_between_inclusive", is_not_weekend: {
$cond: {
if: { $in: [ {$dayOfWeek: "$dates_in_between_inclusive"}, [1, 7] ]},
then: 0,
else: 1
}}}},
{$match: {date: {$nin: holidays_dates_list}}},
{$group: {
_id: "$_id",
days: {$sum: "$is_not_weekend"}
}}
])
Run Code Online (Sandbox Code Playgroud)
假设:
1. every document has at least start_date and end_date fields which are mongodb dates.
2. "holidays_dates_list" is an array of dates which has holidays (may or may not include weekends)
Run Code Online (Sandbox Code Playgroud)
以上查询本身过滤周末。因此,“holidays_dates_list”不需要周末。
| 归档时间: |
|
| 查看次数: |
456 次 |
| 最近记录: |