Easier bulk deletion of Sanity documents, using Sanity CLI
Yesterday I wrote a kind of intricate blog post on how to bulk delete Sanity documents using Sanity CLI, Notepad++ and regex. My closing phrase of the blog post was.
Do you know an easier way?
Luckily for me, Knut Melvær from Sanity knew and took the time out of his busy schedule to enlighten me in the comments section. With this newfound knowledge, I can write this very blog post on how to bulk delete with less hassle.
Installing the tools needed
- Install Sanity CLI.
npm install -g @sanity/cli
- Install GROQ CLI.
npm install -g groq-cli
- If you are running Windows, install FindUtils from GnuWin to get the xargs command. Then add its installation folder to the PATH environment variable.
Bulk delete
With the tools in place, I can bulk delete all documents of type myDocument
with this one-liner.
sanity documents query "*[_type == 'myDocument'][0...20]._id" | groq "*" -o ndjson | xargs sanity documents delete
What happens
The one-liner consists of three parts.
- The query,
sanity documents query "*[_type == 'myDocument'][0...20]._id"
, using Sanity CLI that yields a list of 20 documents ids, in json format, piped to the next part. - The conversion to ndjson,
groq "*" -o ndjson
, using GROQ CLI, piped to the next part. - Finally, xargs is used to pass the list of document ids in ndjson format as arguments to Sanity CLI's document delete,
xargs sanity documents delete
.
Warning
I have been experiencing timeout when deleting more than 50 documents in one go, that's why I have limited to query above to 20. This should not be a problem, so Sanity is digging into it...
Closing words
My motivation for writing blog posts is not to spread the knowledge I possess. My motivation is the knowledge I gain from researching the blog post, and the knowledge I gain from the feedback I receive after publishing the blog post.