Fix “WRONGTYPE Operation against a key holding the wrong kind of value” when using ZLEXCOUNT in Redis

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

To fix this issue, be sure that you pass a sorted set to the ZLEXCOUNT command.

Example of Error

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

ZLEXCOUNT 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 ZLEXCOUNT command.

Solution

The solution is to make sure the key we pass to the ZLEXCOUNT command holds a sorted set.

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

ZLEXCOUNT cats - +

Result:

(integer) 4

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

As expected, it’s a sorted set.