0
0
Redisquery~5 mins

LREM for element removal in Redis

Choose your learning style9 modes available
Introduction
LREM helps you remove specific items from a list in Redis. It makes it easy to clean up or update your list data.
You want to delete all occurrences of a word from a list of tags.
You need to remove a specific user's name from a list of online users.
You want to delete only the first few times a value appears in a list.
You want to keep your list tidy by removing unwanted repeated entries.
Syntax
Redis
LREM key count value
The 'count' controls how many matching elements to remove and from which direction.
If count > 0, remove from head to tail; if count < 0, remove from tail to head; if count = 0, remove all matching elements.
Examples
Removes the first 2 occurrences of "apple" from the list named mylist, starting from the front.
Redis
LREM mylist 2 "apple"
Removes the last occurrence of "banana" from mylist, starting from the end.
Redis
LREM mylist -1 "banana"
Removes all occurrences of "orange" from mylist.
Redis
LREM mylist 0 "orange"
Sample Program
First, we add fruits to the list. Then we remove the first 2 "apple" entries. Finally, we get the full list to see the result.
Redis
RPUSH fruits "apple" "banana" "apple" "orange" "apple"
LREM fruits 2 "apple"
LRANGE fruits 0 -1
OutputSuccess
Important Notes
LREM returns the number of removed elements.
If the list or value does not exist, LREM returns 0 and does nothing.
Use LRANGE to check the list contents after removal.
Summary
LREM removes specific elements from a Redis list.
The count argument controls how many and from which end elements are removed.
It helps keep your list data clean and updated.