在mongoDB中搜索日期和忽略时间 [英] Searching Dates and Ignoring time in mongoDB

查看:341
本文介绍了在mongoDB中搜索日期和忽略时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to query a collection based on a date field. My collection has a field of type date+time stamp. However I would like to ignore the time stamp and just use the date portion. The field is : "enddate" : ISODate("2014-10-10T07:00:00Z"). I am using the following query:

Camps.findOne(

Camps.findOne(

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

但是日期(新的Date())转换为UTC日期,这导致查询不返回所有文档.

but date (new Date()) is converted to UTC date which causes the query not to return all the documents.

任何帮助将不胜感激.

Any help is greatly appreciated.

推荐答案

一种方法是使用 date aggregation operators .例如:

One way to do it would be to use the aggregation framework and take advantage of the date aggregation operators. For example:

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

这篇关于在mongoDB中搜索日期和忽略时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆