How to Use MGET in Redis: Syntax and Examples
Use the
MGET command in Redis to get the values of multiple keys in one call by listing the keys separated by spaces. It returns an array of values corresponding to the keys, with null for keys that do not exist.Syntax
The MGET command retrieves the values of multiple keys in a single call.
- MGET: The command name.
- key1 key2 ... keyN: List of keys you want to get values for.
The command returns an array of values in the same order as the keys. If a key does not exist, its value in the array is null.
redis
MGET key1 key2 key3
Example
This example shows how to set three keys and then retrieve their values using MGET. It demonstrates getting multiple values in one command and handling missing keys.
redis
SET name "Alice" SET age "30" SET city "Paris" MGET name age city country
Output
OK
OK
OK
1) "Alice"
2) "30"
3) "Paris"
4) (nil)
Common Pitfalls
Common mistakes when using MGET include:
- Expecting a single value instead of an array of values.
- Not handling
nullvalues for keys that do not exist. - Passing no keys, which returns an empty array.
Always check the returned array length and values to avoid errors in your application.
redis
MGET # Wrong: No keys passed, returns empty array MGET key1 # Right: Always pass keys and handle nulls MGET key1 key2 key3
Output
1) (empty list or set)
1) "value1"
1) "value1"
2) (nil)
3) "value3"
Quick Reference
| Command | Description |
|---|---|
| MGET key1 key2 ... keyN | Get values of multiple keys at once |
| Returns | Array of values or null for missing keys |
| Use case | Efficiently fetch multiple keys in one call |
Key Takeaways
Use MGET to fetch multiple keys in one Redis call for efficiency.
MGET returns an array with values or null for missing keys.
Always handle null values to avoid errors in your application.
Passing no keys to MGET returns an empty array.
MGET is faster than multiple GET calls for multiple keys.