4
votes

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(

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

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

Any help is greatly appreciated.

1

1 Answers

6
votes

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