【问题标题】:How to query mongoDB for a given date range?如何查询给定日期范围的 mongoDB?
【发布时间】:2021-06-10 05:41:21
【问题描述】:

我正在使用 mongoose 为我的 node.js 应用程序查询给定月份的数据,我接受用户输入的年份和月份。

这就是我正在做的事情

var lastDay = 31
    if (month == 3 || month == 5 || month == 8 || month == 10) lastDay = 30
    else if (month == 1) lastDay = 28

var cookies = await Cookies.find({ 
        docDate: { 
            "$gte": new Date(parseInt(year), parseInt(month), 1),
            "$lte": new Date(parseInt(year), parseInt(month), lastDay)}}).sort("docDate");

当我尝试查询 2 月份的数据库时,我只能在 2 月 26 日之前获得结果,而且结果还包括 1 月份的数据。

请帮我弄清楚我做错了什么。

【问题讨论】:

  • 闰年呢?

标签: mongodb mongoose


【解决方案1】:

我认为问题在于传递给查询的日期。

new Date(2021,01,01); --> 2021-01-31T16:00:00.000Z
new Date(Date.UTC(2021,01,01)); --> 2021-02-01T00:00:00.000Z

如果数据库中的日期字段在UTC 中,请尝试使用new Date(Date.UTC(year, month, day))

【讨论】:

    【解决方案2】:

    使用moment.js库:

    docDate: { 
       "$gte": moment().startOf('month').toDate(),
       "$lte": moment().endOf('month').toDate()
    }
    

    moment() 是当前时间。为了输入具体的日期,例如使用moment(year + '-' + month, "YYYY-MM")

    【讨论】:

    • 使用时刻对我不起作用...当我将时刻用作时刻(“2021-01”)时,数据库不返回任何内容
    • 抱歉,打错字了。必须是 moment()(不带“s”)。请注意,您还打错了"2021- 01"
    猜你喜欢
    • 2021-01-03
    • 1970-01-01
    • 1970-01-01
    • 2018-07-09
    • 2018-09-18
    • 1970-01-01
    • 1970-01-01
    • 2014-09-29
    • 2014-11-28
    相关资源
    最近更新 更多