4

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 Answer 1

6

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 }
         }
     }
   ]
)
Sign up to request clarification or add additional context in comments.

1 Comment

@user3083637, that's great. If the answer resolved your issue, you should consider upvoting/accepting it to encourage the community that's helping us :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.