【问题标题】:How to get all the dates between two dates in mongodb aggregation?如何在mongodb聚合中获取两个日期之间的所有日期?
【发布时间】:2019-09-02 18:43:46
【问题描述】:

如果 start_date 是 '2019-08-10' 而 end_date 是 '2019-09-15' 那么我希望 o/p 为

'2019-08-10'
'2019-08-11'
'2019-08-12'
'2019-08-13'
'2019-08-14'
............
............
............
'2019-09-14'
'2019-09-15'

我尝试使用 $range 函数,但是当日期差异很大(超过 100 天)时,它会抛出错误 "$range requires an ending value that can be represented as a 32-bit integer, found value: 1.57248e+10"

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

【问题讨论】:

  • 这些开始和结束日期是字符串还是真实日期?实际上,必须是真实的日期,否则$subtract 将不起作用...

标签: mongodb mongodb-query aggregation-framework


【解决方案1】:

这行得通。这基本上与您正在做的事情相同,但可以工作,因为繁重的工作是由 $multiply 函数完成的,而不是陷入 $range?我以 20300101 的结束日期对其进行了测试,因此非常大的间隔也可以正常工作。

var d = {
    "start_date": new ISODate("20190810"),
    "end_date": new ISODate("20190915")
};

c = db.foo.aggregate([

{$addFields: {days_diff: {$divide: [{$subtract: ["$end_date", "$start_date"]}, 86400000.0 ]} }}

,{$project: {dates_in_between_inclusive: {
            $map: {
                input: {$range: [0, {$add:["$days_diff",1]}] }, // +1 for inclusive
                as: "dd",
                in: {$add: ["$start_date", {$multiply:["$$dd", 86400000]}]}
            }
        }}},

{$unwind: "$dates_in_between_inclusive"}
                      ]);

产量

{
    "_id" : ObjectId("5d6db092a09f8fe062710b63"),
    "dates_in_between_inclusive" : ISODate("2019-08-10T00:00:00Z")
}
{
    "_id" : ObjectId("5d6db092a09f8fe062710b63"),
    "dates_in_between_inclusive" : ISODate("2019-08-11T00:00:00Z")
}
...

【讨论】:

  • 我是 MongoDB 新手,需要这个 sn-p 来使用,但我不完全理解你在这里做了什么。如果你能解释一下这段代码,那就太好了。
猜你喜欢
  • 1970-01-01
  • 2013-08-09
  • 1970-01-01
  • 2017-06-12
  • 1970-01-01
  • 2014-06-11
  • 1970-01-01
  • 1970-01-01
  • 2021-11-01
相关资源
最近更新 更多