In Redis, the ZMPOPMIN
command removes and returns (pops) members with the lowest scores from the specified sorted set. By default it pops one member, but we can also specify how many members we want to pop.
Syntax
The syntax goes like this:
ZPOPMIN key [count]
Example
Suppose we create the following sorted set:
ZADD cats 1 Meow 2 Fluffy 3 Scratch 4 Purr 5 Bite 6 Bunting
Let’s use the ZPOPMIN
command to pop an element from that sorted set:
ZPOPMIN cats
Result:
1) "Meow" 2) "1"
In this case I didn’t provide the count
option, so it popped the member with the lowest score.
Pop Multiple Elements
We can use the count
option to pop multiple elements. By default, this is set to 1
but we can specify a different number.
ZPOPMIN cats 2
Result:
1) "Fluffy" 2) "2" 3) "Scratch" 4) "3"
This time two members were popped because I specified a count of 2
. When popping multiple members, the members are ordered from the lowest score to the highest.
Let’s take a look at the cats
sorted set now:
ZRANGE cats 0 -1
Result:
1) "Purr" 2) "Bite" 3) "Bunting"
Now there’s only three elements left, because the others have been popped.
When the count
Argument is Greater than the Sorted Set’s Cardinality
If the count
argument is a larger number than the number of elements in the sorted set, then all elements are popped.
Example:
ZPOPMIN cats 10
Result:
1) "Purr" 2) "4" 3) "Bite" 4) "5" 5) "Bunting" 6) "6"
We can see that all elements were popped from our sorted set.
When the Key Doesn’t Exist
If the key doesn’t exist, we get an empty array:
ZPOPMIN oops
Result:
(empty array)
Wrong Data Type
When the key contains the wrong data type, an error is returned:
ZPOPMIN animals
Result:
(error) WRONGTYPE Operation against a key holding the wrong kind of value
In this case, the animals
key contains a set (not a sorted set), and so we got an error.
We can use the TYPE
command to check the key’s data type:
TYPE animals
Result:
set
As suspected, it’s a set.
Alternatives
- Redis also has a
ZMPOP
command that can do the same thing asZPOPMIN
and more. - There’s also a
ZPOPMAX
command that works likeZPOPMIN
, except that it pops the members with the highest scores instead of the lowest. - There’s also a
BZPOPMIN
command which is the blocking variant ofZPOPMIN
. - There’s also a
BZMPOP
command which is the blocking variant ofZMPOP
. - There’s also a
BZPOPMAX
command which is the blocking variant ofZPOPMAX
.