MGET

MGET key [key ...]
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)
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]

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();

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();
    }
}
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();
        }
    }
}
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();
        }
    }
}
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.


    }
}
<?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:

SET key1 "Hello" SET key2 "World" MGET key1 key2 nonexisting

Redis Software and Redis Cloud compatibility

Redis
Software
Redis
Cloud
Notes
✅ Standard
✅ Active-Active
✅ Standard
✅ Active-Active

Return information

Array reply: a list of values at the specified keys.
RATE THIS PAGE
Back to top ↑