In Redis, the LMPOP
command pops one or more elements from the first non-empty list key from the list of provided key names.
The LMPOP
command is similar to LPOP
, except that it can accept multiple keys. It’s also similar to BLPOP
(which accepts multiple keys), except that it can pop multiple elements (BLPOP
can only pop one element).
The LMPOP
command was introduced in Redis 7.0.0.
There’s also an BLMPOP
command, which is the blocking variant of LMPOP
.
Syntax
The syntax goes like this:
LMPOP numkeys key [key ...] LEFT | RIGHT [COUNT count]
The following examples demonstrate this command and its various arguments.
Example
Suppose we create a list like this:
RPUSH scores 1 2 3 4 5 6 7 8 9 10
Result:
(integer) 10
Let’s look at its contents:
LRANGE scores 0 -1
Result:
1) "1" 2) "2" 3) "3" 4) "4" 5) "5" 6) "6" 7) "7" 8) "8" 9) "9" 10) "10"
Here’s an example of using the LMPOP
command against that list and another list:
LMPOP 2 oops scores LEFT COUNT 3
Result:
1) "scores" 2) 1) "1" 2) "2" 3) "3"
In this case, the oops
list was empty, and so LMPOP
popped the first three elements from the scores
list. As mentioned, LMPOP
pops elements only from the first non-empty list key. Seeing as the first list was empty, it popped the specified elements from the second list.
Let’s now use LRANGE
to return all remaining elements in the list:
LRANGE scores 0 -1
Result:
1) "4" 2) "5" 3) "6" 4) "7" 5) "8" 6) "9" 7) "10"
The RIGHT
Argument
In the previous example I used the LEFT
argument. Let’s now use the RIGHT
argument:
LMPOP 2 oops scores RIGHT COUNT 3
Result:
1) "scores" 2) 1) "10" 2) "9" 3) "8"
Now we’ve popped the last three elements from the list.
Let’s use LRANGE
to return all remaining elements in the list:
LRANGE scores 0 -1
Result:
1) "4" 2) "5" 3) "6" 4) "7"
Omit the Count
Here’s what happens when we omit the (optional) COUNT
argument and its associated count:
LMPOP 2 oops scores LEFT
Result:
1) "scores" 2) 1) "4"
It popped one element. We specified LEFT
and so it popped it from the head of the list.
Let’s do it again from the right:
LMPOP 2 oops scores RIGHT
Result:
1) "scores" 2) 1) "7"
Pop All Elements
Specifying a count that’s either as large or larger than the list pops all elements from the list.
First, let’s take another look at the list:
LRANGE scores 0 -1
Result:
1) "5" 2) "6"
We can pop all elements by specifying a count that’s two or higher.
LMPOP 2 oops scores LEFT COUNT 100
Result:
1) "scores" 2) 1) "5" 2) "6"