Creating an array of dates?

I have an “availabilities” collection. Inside this collection could be a few entries that are date based for example:

{
  "_id": "64b03ed794d87927a3066e13",
  "startDateTime": "2023-07-07T18:00:00.000Z",
  "endDateTime": "2023-07-12T15:00:00.000Z",
  "availabilityType": "blackout"
}
{
  "_id": "64b03eb094d87927a3066ddb",
  "startDateTime": "2023-07-03T18:00:00.000Z",
  "endDateTime": "2023-07-06T15:00:00.000Z",
  "availabilityType": "blackout"
} 

I am trying to figure out the best way to create an array of dates for the month and if there is an “availability” for some of the days, then return that within the date array. I thought about creating an array of days using javascript but then I’d have to iterate for each day to see there are any “availabilities” on the day; this seems very inefficient.

Ideally what I am looking to build is something similar to the following:

[
  {
    "date": "2023-07-01",
    "availabilityType": "available"
  },
  {
    "date": "2023-07-02",
    "availabilityType": "available"
  },
  {
    "date": "2023-07-03",
    "availabilityType": "booked" // because there was an availability entry in the collection that is marked as booked
  },
  {
    "date": "2023-07-04",
    "availabilityType": "booked" // because there was an availability entry in the collection that is marked as booked
  },
  {
    "date": "2023-07-05",
    "availabilityType": "booked" // because there was an availability entry in the collection that is marked as booked
  },
  {
    "date": "2023-07-06",
    "availabilityType": "booked" // because there was an availability entry in the collection that is marked as booked
  },
  ... etc up to July 31
]

Any suggestions on how this might be done?

Hi @JeffCi and welcome to MongoDB community forums!!

In order to assist you better, it would be helpful if you could clarify a few of my understanding about the sample document and the expected output shared.

Firstly, for the below document

and

can you confirm if my understanding is correct in that you are wanting to create an array (the output), for example, for the month July using the startDateTime and endDateTime of each document in the availabilities collection?
If my understanding is right, could you also confirm, if the two values for availabilityType as blackout and booked have any inter-dependency or do they imply the same meaning?
Finally, can you let us know the MongoDB version you are on?

Regards
Aasawari

1 Like