In Redis, the MSETNX
command allows us to set multiple keys at once, but only if none of them exist.
This allows us to set multiple keys representing different fields of a single logical object in a way that ensures that either all the fields are set, or none are set.
Syntax
The syntax goes like this:
MSETNX key value [ key value ...]
Which basically means we can set multiple key/value pairs at once.
Example
Here’s a simple example to demonstrate:
MSETNX name "Woof" type "Dog" age "10"
Result:
(integer) 1
In this case, the MSET
operation was successful, and so we got an integer reply of 1
.
We can now use the MGET
command to return the values of each of those keys. Here’s an example of doing just that:
MGET name type age
Result:
1) "Woof" 2) "Dog" 3) "10"
When a Key Already Exists
As mentioned, if any of the keys already exist, nothing is set. Here’s an example:
MSETNX name "Big Woof" age "11"
Result:
(integer) 0
We get an integer reply of 0
, which means nothing was set.
Now let’s get the values again:
MGET name type age
Result:
1) "Woof" 2) "Dog" 3) "10"
As expected, the values haven’t changed since the first example.
If this is a problem for you, use MSET
instead. The MSET
command overwrites any existing values with the new value.