Finding dates and ignoring times in mongoDB
I am trying to query a collection based on a date field. My collection has a date type field + timestamp. However, I would like to ignore the timestamp and just use the date. Field: "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 the date (new date ()) is converted to UTC date which causes the query not to return all documents.
Any help is appreciated.
+2
source to share
1 answer
One way to do this is to use aggregation framework
and take advantage 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 }
}
}
]
)
+5
source to share