themazz
themazz

Reputation: 1147

Mongo returning array of arrays instead of objects

I have the following issue. I have just created a new mongodb instance in my aws account with the same version but the results coming from my php queries come in a different way.

Before I used to get an array of objects but now I get and array of arrays.
For example :

Before:

array(1) {
  [0] =>
  class stdClass#401 (6) {
    public $_id =>
    class MongoDB\BSON\ObjectId#390 (1) {
      public $oid =>
      string(24) "5a685fa82fdc5d031e25451c"
    }
  }
}

Now:

array(1) {
  [0]=>
  object(stdClass)#393 (6) {
    ["_id"]=>
    object(MongoDB\BSON\ObjectId)#390 (1) {
      ["oid"]=>
      string(24) "5a685fa82fdc5d031e25451c"
    }
  }
}

Before I used to access my variables from php using the arrow like :

$document->_id;

but now, after getting the results in that way, I need to get change everything to :

$document['_id'];

Is there any setting (php/mongo server) so I can get the results like previously?

I use the php mongo driver to query my database - e.g :

$query = new Query($filter, $options);
/** @var MongoDB\Driver\Manager $manager */
return $manager->executeQuery($collection,$query)->toArray();

Thank you

Upvotes: 0

Views: 2206

Answers (2)

Koustav
Koustav

Reputation: 615

$cursor->setTypeMap(['root' => 'array', 'document' => 'array', 'array' => 'array']);

Upvotes: 2

solarc
solarc

Reputation: 5738

In the cursor you can specify how it returns the results with setTypemap. I think ['document' => 'stdClass'] will do the trick:

$query = new Query($filter, $options);
/** @var MongoDB\Driver\Manager $manager */
$cursor = $manager->executeQuery($collection, $query);
$cursor->setTypeMap(['document' => 'stdClass']);
return $cursor->toArray();

Upvotes: 3

Related Questions