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

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

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

Example of Error

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

ZCOUNT animals 1 10

Result:

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

Here the animals key contains a list and so we get an error.

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

TYPE animals

Result:

list

As suspected, the key contains a list instead of a sorted set.

Solution

The solution is to make sure the key we pass contains the correct data type. The ZCOUNT command is designed to be used with sorted sets, so we should make sure the specified key contains a sorted set.

Here’s an example of running the command against a key that holds a sorted set:

ZCOUNT cats 1 10

Result:

(integer) 3

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

Let’s verify the data type with the TYPE command:

TYPE cats

Result:

zset

As expected, it’s a sorted set (zset means sorted set).