如何在mongodb聚合中获取两个日期之间的工作日数

时间:2019-08-28 06:27:00

标签: mongodb mongodb-query aggregation-framework aggregate-functions

我有两个日期Start Date: 2019-08-13End Date: 2019-08-20。我希望结束日期与工作日期(不包括节假日)的开始日期之间的差额,因此我的结果为4 2019-08-15是假期,2019-08-172019-08-18是周末。

1 个答案:

答案 0 :(得分:2)

尝试此查询:

OffsetDateTime

假设:

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"}
}}
])

以上查询本身会过滤周末。因此,“ holidays_dates_list”不必有周末。

相关问题