2014-10-10 115 views
2

我正在尝试查询基于日期字段的集合。我的收藏有一个类型日期+时间戳的字段。不过,我想忽略时间戳并只使用日期部分。该字段是:“enddate”:ISODate(“2014-10-10T07:00:00Z”)。我使用下面的查询:搜索日期并忽略mongoDB中的时间

Camps.findOne(

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

但日期(新的Date())被转换成导致查询不返回所有文件的UTC日期

。任何帮助是极大的赞赏

回答

5

一种方式做到这一点是使用了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 } 
     } 
    } 
    ] 
) 
+0

感谢您的回复。它效果很好。 – RayKahn 2014-10-12 17:19:12

+1

@ user3083637,那太好了。如果答案解决了你的问题,你应该考虑'upvoting'/['accepting'](http://stackoverflow.com/help/accepted-answer)它来鼓励那些帮助我们的社区:) – 2014-10-12 20:46:01