See Sanity in action 👀 Join us for a live product demo + Q&A →

Help with sub-array filtering for ticket booking system

3 replies
Last updated: Feb 5, 2023
Hey everyone, I'm trying to do some simple sub-array filtering but I can't figure out the right syntax for the life of me.
  _type == "seat"
  && $show in locks[].show
  // Cannot figure out the syntax to do this:
  && count([dateTime(locks[].lockTime) > dateTime(now() - 60*5)]) > 0
The context is a ticket booking system - I need to return seats that have had a "lock" from the front-end placed on them within the past 5 minutes.
The structure of the seat data looks like the attached image. There's an array of locks, and each lock has the id of the show that it's being booked for and the time it was locked. (Didn't make the shows references because this will never be interacted with by an end-user. The field will be hidden.)
I can get a list of locks for the show id that I want, but filtering those locks by the current time isn't quite working. I just can't get the right syntax to return only the IDs with locks less than 5 minutes old.

Thanks for the help!
Feb 4, 2023, 11:34 AM
I think your problem is that
returns a string, which you can’t do arithmetic on. Instead you should convert it. The following will give you the number of seconds between now and `lockTime`:
dateTime(now()) - dateTime(lockTime)
So you could do something like:

dateTime(now()) - dateTime(lockTime) < 300
…which returns true if the lock time is within the last 5 minutes.

Alternative you can send the full “5 minutes ago” timestamp as a parameter, and then you can use it for comparison:

dateTime(lockTime) > dateTime($time):
The other thing that’s wrong here is the counting part:

count([dateTime(locks[].lockTime) > dateTime(now() - 60*5)])
You want to filter the
, so you want an expression like this:
So something like this should work:

count(locks[dateTime(now()) - dateTime(lockTime) < 300])
Feb 4, 2023, 1:36 PM
It's working perfectly, thank you so much! Really appreciate the quick help 🧡
Feb 5, 2023, 1:32 AM
Feb 5, 2023, 1:53 PM – build remarkable experiences at scale

Sanity is a customizable solution that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Categorized in