Redis LREM – How to delete multiple occurrences of an element from a list

5 years ago Lalit Bhagtani 0

In this tutorial, we will learn about how to delete one or more occurrences of an element from a list value stored at a key. For this, we will use a Redis LREM command. 

LREM Command

This command removes first count occurrences of the specified element from a list value stored at a key. The count argument passed in the LREM command influences the operation in the following ways :-

  1. count > 0 :- Removes count occurrences of a specified element moving from head (start) to tail (end).
  2. count < 0 :- Removes count occurrences of a specified element moving from the tail (tail) to head (start).
  3. count = 0 :- Removes all occurrences of a specified element.

A non-existing key is interpreted as an empty list, so the command will always return 0.

If the key exists but value stored at the key is not of list datatype, an error is returned. The syntax of Redis LREM command is as follows :- 

Syntax :-

redis host:post> LREM <keyname> <count> <element>

Output :- 

- (integer) reply, representing number of elements deleted from the list.
- Error, if key exist and value stored at the key is not a list.

Example :-

Redis LREM

References :-

  1. LREM Command Docs

That’s all for how to delete one or more occurrences of specific element from a list value stored in redis datastore. If you liked it, please share your thoughts in comments section and share it with others too.

<- List Commands