I have a scenario where I need to retrieve data for a specific month. How can I determine the start and end dates of a given month?
Here is a snippet of the code:
{"_id":"5e00bc55c31ecc38d023b156","heat":20,"humidity":10,"deviceId":"a-1","template":"13435158964","entryDayTime":"2019-12-23T13:08:37.841Z"},
{"_id":"5e00bbd2c31ecc38d023b155","heat":20,"humidity":10,"deviceId":"a-1","template":"13435158964","entryDayTime":"2019-12-23T13:06:26.366Z"},
{"_id":"5df4a8fb46b9da1e2c0731df","heat":88,"humidity":80,"deviceId":"a-1","template":"13435158964","entryDayTime":"2019-12-14T09:18:51.892Z"},
{"_id":"5e00b50bc127260398cf51dd","heat":20,"humidity":10,"deviceId":"a-1","template":"13435158964","entryDayTime":"2019-12-23T12:37:31.127Z"},
{"_id":"5df20e44e7c51b4bd0095af3","heat":41,"humidity":26,"deviceId":"a-1","template":"13435158964","entryDayTime":"2019-12-12T09:54:12.375Z"}
Code snippet without using moment.js
Payload:
{
"deviceId":"a-1",
"year":2019,
"month":"December"
}
Collection.aggregate([
{
$match: {
"deviceId": payload.deviceId,
"entryDayTime": {
$lt: new Date(`${payload.month},${payload.year},2`).toISOString(),
$gte: new Date(`${payload.month},${payload.year},31`).toISOString()
}
}
}
])
The time ranges obtained in console (times passed in the aggregate function) are as follows:
2019-12-01T18:30:00.000Z
2019-12-30T18:30:00.000Z
Code snippet using moment.js
Payload:
{
"deviceId":"a-1",
"year":2019,
"month":10
}
I also attempted to use moment.js. However, the times generated do not match the database's time format.
Collection.aggregate([
{
$match: {
"deviceId": payload.deviceId,
"entryDayTime": {
$lt:moment([payload.year]).month(payload.month).startOf('month').tz('Asia/Kolkata').format(),
$gte:moment([payload.year]).month(payload.month).endOf('month').tz('Asia/Kolkata').format()
}
}
}
])
The timestamps displayed in console are:
2019-11-01T00:00:00+05:30
2019-11-30T23:59:59+05:30
If moment.js is the preferred option, how can the time format be modified to match the time format in the sample code?