Using aggregation for business logic to find open slots for appointment booking?

We are doing appointment booking, currently all logic is in our application, we just fetch all data for a day from MongoDB. With more appointments at the same day this starts to get slow, so I am wondering if we can put the “business logic” into a MongoDB aggregation?


  • Entities are house (A), floor (A.1) and room (A.1.1)
  • Open hours for every floor (9-10, 11-12, 15-16, 17-18h)
  • Existing booking might not align to the official open hours
  • Parallel appointment limits: 1 per room, 2 per floor, 3 per house.

Logic for getting open slots for room A.1.1 on 2022-10-01:

I can’t wrap my head around this, is this aggregation result possible with a MongoDB aggregation?