0
0
Redisquery~5 mins

MSET and MGET for bulk operations in Redis

Choose your learning style9 modes available
Introduction

MSET and MGET let you save or get many values at once in Redis. This saves time and makes your work faster.

You want to save multiple settings for a user in one go.
You need to get prices of many products quickly.
You want to update several counters at the same time.
You want to fetch multiple session data for users in one request.
Syntax
Redis
MSET key1 value1 key2 value2 ... keyN valueN
MGET key1 key2 ... keyN

MSET sets many keys and values in one command.

MGET gets the values of many keys in one command.

Examples
This saves three keys with their values at once.
Redis
MSET name "Alice" age "30" city "Paris"
This gets the values of the three keys in the same order.
Redis
MGET name age city
Save names of three products quickly.
Redis
MSET product1 "Book" product2 "Pen" product3 "Notebook"
Retrieve the names of the three products in one call.
Redis
MGET product1 product2 product3
Sample Program

First, we save three users' names with MSET. Then, we get all three names with MGET.

Redis
MSET user1 "John" user2 "Jane" user3 "Doe"
MGET user1 user2 user3
OutputSuccess
Important Notes

If a key does not exist in MGET, Redis returns nil for that key.

MSET is atomic, so all keys are set at once or none at all.

Summary

MSET saves many keys and values in one command.

MGET fetches many values by keys in one command.

Using these commands makes Redis faster and simpler for bulk data.