How to use a Patch Query to Unset an Array Element
Sure! When you want to unset (remove) an array element using a patch query in Sanity, you can use JSONMatch expressions to target specific items based on their values.
Here's a basic example using the unset operation:
client.patch('document-id')
.unset(['arrayField[@ == "valueToRemove"]'])
.commit()This removes any array item that equals "valueToRemove".
For your specific case (removing items from a save array based on userId):
client.patch('Ein4V1AQOMSZUazhbENMD4')
.unset(['save[userId == "112412412793415669744"]'])
.commit()This will remove any object in the save array where the userId matches "112412412793415669744".
More examples:
Remove by nested reference:
.unset(['save[postedBy._ref == "112412412793415669744"]'])Remove by _key:
.unset(['save[_key == "67f3bb67-0220-4b04-9b5b-fa76e2dc9e39"]'])The key is using the JSONMatch syntax inside square brackets to filter which array elements to target. The @ symbol represents the current item when matching primitive values, or you can use field names like userId or person.id for nested properties.
You can find more details about patch operations and the JSONMatch syntax in the Sanity docs.
Sanity – Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.