Fix “WRONGTYPE Operation against a key holding the wrong kind of value” when using ZPOPMIN, ZPOPMAX, BZPOPMIN, or BZPOPMAX in Redis

If you get an error that reads “WRONGTYPE Operation against a key holding the wrong kind of value” when using the ZPOPMIN or ZPOPMAX commands in Redis, it’s because you’re passing a key with the wrong data type.

The same issue can apply when using the blocking variants of these commands (BZPOPMIN and BZPOPMAX).

To fix this issue, make sure you pass a sorted set to these commands.

Example of Error

Here’s an example of code that causes the error:

ZPOPMIN animals

Result:

(error) WRONGTYPE Operation against a key holding the wrong kind of value

In my case, the animals key holds a set (not a sorted set), which is why I got the error.

We can use the TYPE command to check a key’s type:

TYPE animals

Result:

set

As suspected, the key holds a set, which is the wrong data type for the ZPOPMIN command (and the ZPOPMAX, BZPOPMIN, and BZPOPMAX commands).

Solution

The solution is to make sure the keys we pass to ZPOPMIN (and ZPOPMAX, BZPOPMIN, and BZPOPMAX) hold a sorted set.

Let’s replace the animals key with another key that holds a sorted set:

ZPOPMIN cats

Result:

1) "Meow"
2) "1"

This time we didn’t get the error. That’s because the cats key holds a sorted set.

Let’s check:

TYPE cats

Result:

zset

It’s a sorted set, as expected.