Advertisement
Intermediate Redis, RedisJSON

How do you atomically increment a numeric value nested within a JSON document using RedisJSON?

Short answer

You use the JSON.NUMINCRBY command, specifying the document key, the path to the specific numeric field, and the amount to increase it by, which atomically updates that specific nested value, making it safe even if multiple clients are trying to update the same field…

Save Redis mock interview
Advertisement
AModel answer
You use the JSON.NUMINCRBY command, specifying the document key, the path to the specific numeric field, and the amount to increase it by, which atomically updates that specific nested value, making it safe even if multiple clients are trying to update the same field simultaneously.
Example

JSON.NUMINCRBY product:55 $.stock -1

Real-world example
An inventory system atomically decreases a product's stock count, which is nested within a larger JSON document, using JSON.NUMINCRBY, safely handling many simultaneous purchases without any risk of an incorrect final count.
Likely follow-ups
  • What happens if the target field is not actually a numeric value?
  • Can JSON.NUMINCRBY target multiple matching fields at once using a wildcard path?
Related topics