Running a patch commit to a set of documents at once in Sanity.io using a bulk deletion script.
Yes, you can definitely apply patch operations to multiple documents at once! Sanity provides several approaches depending on your specific needs:
Using Transactions
The most straightforward way to patch multiple documents atomically is using transactions. Transactions allow you to batch multiple patch operations together with all-or-nothing execution:
await client
.transaction()
.patch('doc-id-1', p => p.set({ status: 'published' }))
.patch('doc-id-2', p => p.set({ status: 'published' }))
.patch('doc-id-3', p => p.set({ status: 'published' }))
.commit()This ensures either all patches succeed or none are applied, maintaining data consistency.
Bulk Updates with Batching
For updating many documents (100+), you'll want to batch your operations and respect rate limits. Here's a pattern that works well:
import pThrottle from 'p-throttle';
const throttle = pThrottle({
limit: 25, // Max 25 requests per second
interval: 1000
});
// Query for documents you want to update
const documents = await client.fetch('*[_type == "post" && status == "draft"]');
// Process in batches
const batchSize = 100;
for (let i = 0; i < documents.length; i += batchSize) {
const batch = documents.slice(i, i + batchSize);
const transaction = client.transaction();
batch.forEach(doc => {
transaction.patch(doc._id, p => p.set({ status: 'published' }));
});
await throttle(() => transaction.commit())();
}Important Considerations
- Transaction size: Keep transaction payloads under 500kB
- Rate limits: Maximum 25 requests per second
- Field initialization: When using operations like
inc(), usesetIfMissing()first to ensure the field exists
The patches documentation provides more details on available patch operations like set, unset, insert, and array manipulation.
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.