MGET
MGET key [key ...]
mget(
keys: KeysT,
*args: EncodableT
) → ResponseT
MGET(
keys: Array<RedisArgument>
) → Any
mget(
keys: String...
) → List<String> // Multi bulk reply
mget(
keys: K... // the keys.
) → List<KeyValue<K, V>> // Long array-reply list of values at the specified keys.
mget(
channel: KeyValueStreamingChannel<K, V>, // the channel.
keys: K... // the keys.
) → Long // Long array-reply list of values at the specified keys.
mget(
keys: K... // the keys.
) → RedisFuture<List<KeyValue<K, V>>> // Long array-reply list of values at the specified keys.
mget(
channel: KeyValueStreamingChannel<K, V>, // the channel.
keys: K... // the keys.
) → RedisFuture<Long> // Long array-reply list of values at the specified keys.
mget(
keys: K... // the keys.
) → Flux<KeyValue<K, V>> // Long array-reply list of values at the specified keys. @deprecated since 6.0 in favor of consuming large results through the org.reactivestreams.Publisher returned by #mget.
mget(
channel: KeyValueStreamingChannel<K, V>, // the channel.
keys: K... // the keys.
) → Mono<Long> // Long array-reply list of values at the specified keys. @deprecated since 6.0 in favor of consuming large results through the org.reactivestreams.Publisher returned by #mget.
MGet(
ctx: context.Context,
keys: ...string
) → *SliceCmd
No method signature available for this client.
No method signature available for this client.
mget(
$keyOrKeys: string[]|string,
string ...$keys = null: Any
) → array
mget(
key: K
) → (Vec<Option<String>>)
mget(
key: K
) → (Vec<Option<String>>)
- Available since:
- Redis Open Source 1.0.0
- Time complexity:
- O(N) where N is the number of keys to retrieve.
- ACL categories:
-
@read,@string,@fast, - Compatibility:
- Redis Software and Redis Cloud compatibility
Note:
This command's behavior varies in clustered Redis environments. See the multi-key operations page for more information.Returns the values of all specified keys.
For every key that does not hold a string value or does not exist, the special
value nil is returned.
Because of this, the operation never fails.
Examples
Returns the values of all specified keys.
> SET key1 "Hello"
"OK"
> SET key2 "World"
"OK"
> MGET key1 key2 nonexisting
1) "Hello"
2) "World"
3) (nil)
Redis CLI guide
Also, check out our other client tools
Redis Insight
and
Redis for VS Code.
import redis
r = redis.Redis(decode_responses=True)
r.set("key1", "Hello")
r.set("key2", "World")
mget_result = r.mget("key1", "key2", "nonexisting")
print(mget_result)
# >>> ['Hello', 'World', None]
-
Sets the string value of a key, ignoring its type. The key is created if it doesn't exist.
-
set(
- name: KeyT,
- value: EncodableT,
- ex: Optional[ExpiryT] = None,
- px: Optional[ExpiryT] = None,
- nx: bool = False,
- xx: bool = False,
- keepttl: bool = False,
- get: bool = False,
- exat: Optional[AbsExpiryT] = None,
- pxat: Optional[AbsExpiryT] = None,
- ifeq: Optional[Union[bytes, str]] = None,
- ifne: Optional[Union[bytes, str]] = None,
- ifdeq: Optional[str] = None,
- ifdne: Optional[str] = None
-
set(
import assert from 'node:assert';
import { createClient } from 'redis';
const client = createClient();
await client.connect().catch(console.error);
await client.set('key1', 'Hello');
await client.set('key2', 'World');
const mgetResult = await client.mGet(['key1', 'key2', 'nonexisting']);
console.log(mgetResult); // >>> [ 'Hello', 'World', null ]
await client.close();
import assert from 'node:assert';
import { Redis } from 'ioredis';
const redis = new Redis();
await redis.set('key1', 'Hello');
await redis.set('key2', 'World');
const mgetResult = await redis.mget('key1', 'key2', 'nonexisting');
console.log(mgetResult); // >>> ['Hello', 'World', null]
redis.disconnect();
-
Sets the string value of a key, ignoring its type. The key is created if it doesn't exist.
-
set(
- key: RedisKey,
- value: string | Buffer | number,
- callback?: Callback<"OK">
-
set(
- key: RedisKey,
- value: string | Buffer | number,
- get: "GET",
- callback?: Callback<string | null>
-
set(
- key: RedisKey,
- value: string | Buffer | number,
- nx: "NX",
- callback?: Callback<"OK" | null>
-
set(
- key: RedisKey,
- value: string | Buffer | number,
- nx: "NX",
- get: "GET",
- callback?: Callback<string | null>
-
set(
- key: RedisKey,
- value: string | Buffer | number,
- xx: "XX",
- callback?: Callback<"OK" | null>
-
set(
import redis.clients.jedis.RedisClient;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
public class CmdsStringExample {
public void run() {
RedisClient jedis = RedisClient.create("redis://localhost:6379");
String incrResult1 = jedis.set("mykey", "10");
System.out.println(incrResult1); // >>> OK
long incrResult2 = jedis.incr("mykey");
System.out.println(incrResult2); // >>> 11
String incrResult3 = jedis.get("mykey");
System.out.println(incrResult3); // >>> 11
// Tests for 'incr' step.
String mgetResult1 = jedis.set("key1", "Hello");
System.out.println(mgetResult1); // >>> OK
String mgetResult2 = jedis.set("key2", "World");
System.out.println(mgetResult2); // >>> OK
java.util.List<String> mgetResult3 = jedis.mget("key1", "key2", "nonexisting");
System.out.println(mgetResult3); // >>> [Hello, World, null]
// Tests for 'mget' step.
jedis.close();
}
}
-
Sets the string value of a key, ignoring its type. The key is created if it doesn't exist.
-
set(
- key: byte[],
- value: byte[]
-
set(
- key: byte[],
- value: byte[],
- params: SetParams // key if it already exists. EX|PX, expire time units: EX = seconds; PX = milliseconds
-
set(
- key: String,
- value: String
-
set(
- key: String,
- value: String,
- params: SetParams // key if it already exists. EX|PX, expire time units: EX = seconds; PX = milliseconds
-
set(
package io.redis.examples.async;
import io.lettuce.core.RedisClient;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.async.RedisAsyncCommands;
import java.util.concurrent.CompletableFuture;
public class CmdsStringExample {
public void run() {
RedisClient redisClient = RedisClient.create("redis://localhost:6379");
try (StatefulRedisConnection<String, String> connection = redisClient.connect()) {
RedisAsyncCommands<String, String> asyncCommands = connection.async();
CompletableFuture<Void> mgetExample = asyncCommands.set("key1", "Hello")
.thenCompose(res1 -> asyncCommands.set("key2", "World"))
.thenCompose(res2 -> asyncCommands.mget("key1", "key2", "nonexisting"))
.thenAccept(res3 -> {
System.out.println(res3);
// >>> [KeyValue[key1, Hello], KeyValue[key2, World], KeyValue[nonexisting, null]]
})
.toCompletableFuture();
mgetExample.join();
} finally {
redisClient.shutdown();
}
}
}
-
Sets the string value of a key, ignoring its type. The key is created if it doesn't exist.
-
set(
- key: K, // the key.
- value: V // the value.
-
set(
- key: K, // the key.
- value: V, // the value.
- setArgs: SetArgs // the setArgs.
-
set(
-
Atomically returns the string values of one or more keys.
-
mget(
- keys: K... // the keys.
-
mget(
- channel: KeyValueStreamingChannel<K, V>, // the channel.
- keys: K... // the keys.
-
mget(
package io.redis.examples.reactive;
import io.lettuce.core.RedisClient;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.reactive.RedisReactiveCommands;
import reactor.core.publisher.Mono;
public class CmdsStringExample {
public void run() {
RedisClient redisClient = RedisClient.create("redis://localhost:6379");
try (StatefulRedisConnection<String, String> connection = redisClient.connect()) {
RedisReactiveCommands<String, String> reactiveCommands = connection.reactive();
Mono<Void> mgetExample = reactiveCommands.set("key1", "Hello")
.flatMap(res1 -> reactiveCommands.set("key2", "World"))
.flatMap(res2 -> reactiveCommands.mget("key1", "key2", "nonexisting").collectList())
.doOnNext(res3 -> {
System.out.println(res3);
// >>> [KeyValue[key1, Hello], KeyValue[key2, World], KeyValue[nonexisting, null]]
})
.then();
mgetExample.block();
} finally {
redisClient.shutdown();
}
}
}
-
Sets the string value of a key, ignoring its type. The key is created if it doesn't exist.
-
set(
- key: K, // the key.
- value: V // the value.
-
set(
- key: K, // the key.
- value: V, // the value.
- setArgs: SetArgs // the setArgs.
-
set(
-
Atomically returns the string values of one or more keys.
-
mget(
- keys: K... // the keys.
-
mget(
- channel: KeyValueStreamingChannel<K, V>, // the channel.
- keys: K... // the keys.
-
mget(
package example_commands_test
import (
"context"
"fmt"
"github.com/redis/go-redis/v9"
)
func ExampleClient_cmd_incr() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
incrResult1, err := rdb.Set(ctx, "mykey", "10", 0).Result()
if err != nil {
panic(err)
}
fmt.Println(incrResult1) // >>> OK
incrResult2, err := rdb.Incr(ctx, "mykey").Result()
if err != nil {
panic(err)
}
fmt.Println(incrResult2) // >>> 11
incrResult3, err := rdb.Get(ctx, "mykey").Result()
if err != nil {
panic(err)
}
fmt.Println(incrResult3) // >>> 11
}
func ExampleClient_cmd_mget() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
if err := rdb.Set(ctx, "key1", "Hello", 0).Err(); err != nil {
panic(err)
}
if err := rdb.Set(ctx, "key2", "World", 0).Err(); err != nil {
panic(err)
}
mgetResult, err := rdb.MGet(ctx, "key1", "key2", "nonexisting").Result()
if err != nil {
panic(err)
}
fmt.Println(mgetResult) // >>> [Hello World <nil>]
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <hiredis/hiredis.h>
int main(int argc, char **argv) {
redisContext *c = redisConnect("127.0.0.1", 6379);
if (c == NULL || c->err) {
if (c) {
printf("Connection error: %s\n", c->errstr);
redisFree(c);
} else {
printf("Connection error: can't allocate redis context\n");
}
return 1;
}
redisReply *reply = redisCommand(c, "SET key1 Hello");
freeReplyObject(reply);
reply = redisCommand(c, "SET key2 World");
freeReplyObject(reply);
reply = redisCommand(c, "MGET key1 key2 nonexisting");
for (size_t i = 0; i < reply->elements; i++) {
if (i > 0) {
printf(", ");
}
if (reply->element[i]->type == REDIS_REPLY_NIL) {
printf("null");
} else {
printf("%s", reply->element[i]->str);
}
}
printf("\n");
// >>> Hello, World, null
freeReplyObject(reply);
redisReply *cleanup2 = redisCommand(c, "DEL key1 key2 nonexisting");
freeReplyObject(cleanup2);
redisFree(c);
return 0;
}
using NRedisStack.Tests;
using StackExchange.Redis;
public class CmdsStringExample
{
public void Run()
{
var muxer = ConnectionMultiplexer.Connect("localhost:6379");
var db = muxer.GetDatabase();
// Tests for 'append1' step.
// Tests for 'append2' step.
// Tests for 'decr' step.
// Tests for 'decrby' step.
// Tests for 'get' step.
// Tests for 'getdel' step.
// Tests for 'getex' step.
// Tests for 'getrange' step.
// Tests for 'getset' step.
bool incrResult1 = db.StringSet("mykey", "10");
Console.WriteLine(incrResult1); // >>> true
long incrResult2 = db.StringIncrement("mykey");
Console.WriteLine(incrResult2); // >>> 11
RedisValue incrResult3 = db.StringGet("mykey");
Console.WriteLine(incrResult3); // >>> 11
// Tests for 'incr' step.
// Tests for 'incrby' step.
// Tests for 'incrbyfloat' step.
// Tests for 'lcs1' step.
// Tests for 'lcs2' step.
// Tests for 'lcs3' step.
// Tests for 'lcs4' step.
// Tests for 'lcs5' step.
bool mgetResult1 = db.StringSet("key1", "Hello");
bool mgetResult2 = db.StringSet("key2", "World");
RedisValue[] mgetResult3 = db.StringGet(new RedisKey[] { "key1", "key2", "nonexisting" });
Console.WriteLine(string.Join(", ", mgetResult3.Select(v => v.IsNull ? "null" : v.ToString())));
// >>> Hello, World, null
// Tests for 'mget' step.
// Tests for 'mset' step.
// Tests for 'msetnx' step.
// Tests for 'psetex' step.
// Tests for 'set' step.
// Tests for 'setex' step.
// Tests for 'setnx' step.
// Tests for 'setrange1' step.
// Tests for 'setrange2' step.
// Tests for 'strlen' step.
// Tests for 'substr' step.
}
}
-
Sets the string value of a key, ignoring its type. The key is created if it doesn't exist.
-
StringSet(
- key: RedisKey,
- value: RedisValue,
- expiry: TimeSpan?, // The expiry to set.
- when: When // Which condition to set the value under (defaults to always).
-
StringSet(
- key: RedisKey,
- value: RedisValue,
- expiry: TimeSpan?, // The expiry to set.
- when: When, // Which condition to set the value under (defaults to always).
- flags: CommandFlags // The flags to use for this operation.
-
StringSet(
- key: RedisKey,
- value: RedisValue,
- expiry: TimeSpan?, // The expiry to set.
- keepTtl: bool,
- when: When, // Which condition to set the value under (defaults to always).
- flags: CommandFlags // The flags to use for this operation.
-
StringSet(
- key: RedisKey,
- value: RedisValue,
- expiry: Expiration, // The expiry to set.
- when: ValueCondition, // Which condition to set the value under (defaults to always).
- flags: CommandFlags // The flags to use for this operation.
-
StringSet(
- values: KeyValuePair<RedisKey, RedisValue>[], // The keys and values to set.
- when: When, // Which condition to set the value under (defaults to always).
- flags: CommandFlags // The flags to use for this operation.
-
StringSet(
<?php
use PHPUnit\Framework\TestCase;
use Predis\Client as PredisClient;
class CmdsStringTest
{
public function testCmdsString() {
$r = new PredisClient([
'scheme' => 'tcp',
'host' => '127.0.0.1',
'port' => 6379,
'password' => '',
'database' => 0,
]);
$r->set('key1', 'Hello');
$r->set('key2', 'World');
$mgetResult = $r->mget(['key1', 'key2', 'nonexisting']);
echo json_encode($mgetResult) . PHP_EOL; // >>> ["Hello","World",null]
}
}
mod cmds_string_tests {
use redis::Commands;
fn run() {
let mut r = match redis::Client::open("redis://127.0.0.1") {
Ok(client) => match client.get_connection() {
Ok(conn) => conn,
Err(e) => {
println!("Failed to connect to Redis: {e}");
return;
}
},
Err(e) => {
println!("Failed to create Redis client: {e}");
return;
}
};
if let Ok(res) = r.set("key1", "Hello") {
let _: String = res;
}
if let Ok(res) = r.set("key2", "World") {
let _: String = res;
}
match r.mget(&["key1", "key2", "nonexisting"]) {
Ok(mget_result) => {
let mget_result: Vec<Option<String>> = mget_result;
println!("{mget_result:?}"); // >>> [Some("Hello"), Some("World"), None]
}
Err(e) => {
println!("Error getting values: {e}");
}
}
}
}
mod cmds_string_tests {
use redis::AsyncCommands;
async fn run() {
let mut r = match redis::Client::open("redis://127.0.0.1") {
Ok(client) => match client.get_multiplexed_async_connection().await {
Ok(conn) => conn,
Err(e) => {
println!("Failed to connect to Redis: {e}");
return;
}
},
Err(e) => {
println!("Failed to create Redis client: {e}");
return;
}
};
if let Ok(res) = r.set("key1", "Hello").await {
let _: String = res;
}
if let Ok(res) = r.set("key2", "World").await {
let _: String = res;
}
match r.mget(&["key1", "key2", "nonexisting"]).await {
Ok(mget_result) => {
let mget_result: Vec<Option<String>> = mget_result;
println!("{mget_result:?}"); // >>> [Some("Hello"), Some("World"), None]
}
Err(e) => {
println!("Error getting values: {e}");
}
}
}
}
Give these commands a try in the interactive console:
Redis Software and Redis Cloud compatibility
| Redis Software |
Redis Cloud |
Notes |
|---|---|---|
| ✅ Standard |
✅ Standard |
Return information
Array reply: a list of values at the specified keys.
Array reply: a list of values at the specified keys.