I have a document that describes a Practitioner like this
{
name: String;
schedules: {
weekend: [Number],
timings: [{
from: {hour: Number, minute: Number},
to: {hour: Number, minute: Number}
}]
}
}
I want a way to check if a date hours and minutes are included in the timings array using mongoose/mongodb but I am unable to figure this out as I was not able to find any documentation/question about this issue
Edit 1:
my input value is a javascript ISO date, and the expected result is true or false.
CodePudding user response:
Use $dateToParts, it gives a result like this:
"timeParts" : {
"isoWeekYear" : 2021.0,
"isoWeek" : 41.0,
"isoDayOfWeek" : 1.0,
"hour" : 19.0,
"minute" : 58.0,
"second" : 56.0,
"millisecond" : 685.0
}
Then you can compare fields isoDayOfWeek
, hour
and minute
with your values. As you did not provide any input values or expected result, it is difficult for me to propose a concrete solution,
CodePudding user response:
Query
- instead of
ISODate("2017-01-01T02:46:12Z")
put your date variable in both places - the first let creates a date variable to be used for the comparison
- reduce starting from false
- if no find match yet
- check if from_date(convert first) <= your_date <= to_date(convert_first)
- else if match is already found keep the true value
- if at least one matches all reduce will evaluate to true
- set that true/false value to a new field
- you can filter it after if you want, to keep false or true documents
aggregate(
[{"$set":
{"date-in-timings":
{"$let":
{"vars":
{"your_date":
{"$dateFromParts":
{"year": 2021,
"hour": {"$hour": ISODate("2017-01-01T02:46:12Z")},
"minute": {"$minute": ISODate("2017-01-01T02:46:12Z")}}}},
"in":
{"$reduce":
{"input": "$schedules.timings",
"initialValue": false,
"in":
{"$cond":
[{"$not": ["$$value"]},
{"$and":
[{"$gte":
["$$your_date",
{"$dateFromParts":
{"year": 2021,
"hour": "$$this.from.hour",
"minute": "$$this.from.minute"}}]},
{"$lte":
["$$your_date",
{"$dateFromParts":
{"year": 2021,
"hour": "$$this.to.hour",
"minute": "$$this.to.minute"}}]}]}, "$$value"]}}}}}}}])