【问题标题】:Searching Dates and Ignoring time in mongoDB在 mongoDB 中搜索日期并忽略时间
【发布时间】:2014-10-10 21:47:47
【问题描述】:

我正在尝试根据日期字段查询集合。我的收藏有一个日期+时间戳类型的字段。但是我想忽略时间戳,只使用日期部分。该字段是:“结束日期”:ISODate(“2014-10-10T07:00:00Z”)。我正在使用以下查询:

Camps.findOne(

        { $and: [ {status: 1} , {camp_id: pCampID} , {$or: [ {enddate: null}, {enddate: {$gte: new Date()} } ] } ] },...

但是日期 (new Date()) 被转换为 UTC 日期,这会导致查询不返回所有文档。

非常感谢任何帮助。

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    一种方法是使用aggregation framework 并利用date aggregation operators。例如:

    db.camps.aggregate(
       [
         // Perform the initial match to filter docs by 'status' and 'camp_id'
         {
           $match:
             {
               status: 1,
               camp_id: pCampID
             }
         },
         // Extract the year, month and day portions of the 'enddate' 
         {
           $project:
             {
               year: { $year: "$enddate" },
               month: { $month: "$enddate" },
               day: { $dayOfMonth: "$enddate" },
               status: 1,
               camp_id: 1
             }
         },
         // Filter by date - Replace hard-coded values with values you want
         {
           $match:
             {
               year: { $gte: 2014 },
               month: { $gte: 10 },
               day: { $gte: 10 }
             }
         }
       ]
    )
    

    【讨论】:

    • @user3083637,太好了。如果答案解决了您的问题,您应该考虑upvoting/accepting 来鼓励帮助我们的社区:)
    猜你喜欢
    • 2015-06-30
    • 1970-01-01
    • 1970-01-01
    • 2017-12-07
    • 2016-03-15
    • 2019-03-18
    • 2018-01-25
    • 1970-01-01
    • 2012-10-27
    相关资源
    最近更新 更多