Search code examples
phplaravelmongodbindexing

How to get indices using Jenssegers Mongodb


I'm needing to get the indexes of a collection in mongodb using laravel, I know that in mongo compass you can use the $ indexStats which returns the indexes, try to replicate the same as follows

DB::connection('mongodb')->collection("audience")->timeout(-1)->raw(function($collection){
    return $collection->aggregate([
        [
           '$indexStats' => new \stdClass()
        ]
    ], ["allowDiskUse" => true]);
});

But with a dd () check the result and it was the following

MongoDB\Driver\Cursor {#2009}

The truth is that I would not know what that is, if someone knows what I am doing wrong or how to obtain the indexes it would help me a lot

Thank you very much for your time


Solution

  • I just found the solution, it was simply that MongoDB\Driver\Cursor{# 2009} has to be converted into an array, then I detail how the code is

    $query = DB::connection('mongodb')->collection("audience")->raw(function($collection){
            return $collection->aggregate([
                [
                    '$indexStats' => new \stdClass()
                ]
            ], ["allowDiskUse" => true]);
        });
    dd($query->toArray());
    

    And in case you need to convert it to a laravel collection I do it in the following way

    dd(collect(json_decode(\MongoDB\BSON\toJSON(\MongoDB\BSON\fromPHP($query->toArray())), true)));
    

    I convert it to a json, decode it and finally use the collect function.

    I hope it helps someone. Greetings :D