4
votes

I'm having issues with the new mongodb driver for php. While iterator_to_array works ok for ->find, if I only return one document it has MongoDB\Model\BSONDocument format.

$result = $db->clients->findOne(array('_id' => $id));
$result = (array) $result;

In Mongo the document looks something like:

{ 
    "_id" : ObjectId("3894713i4b13iu412"), 
    "active" : true, 
    "logo" : "this is logo", 
    "settings" : {
        "email" : "days", 
        "testMode" : false
    }, 
    "stats" : {
        "f" : {
            "all" : [
                {
                    "count" : NumberLong(15846), 
                    "sum" : NumberLong(149479)
                }, 
                {
                    "count" : NumberLong(15846), 
                    "sum" : NumberLong(148891)
                }, 
                {
                    "count" : NumberLong(15846), 
                    "sum" : {
                        "1" : NumberLong(15522), 
                        "2" : NumberLong(324)
                    }
                }
            ]
        }, 
        "l" : {
            "order" : ISODate("2016-12-05T09:10:53.855+0000"), 
            "feedback" : ISODate("2016-12-05T08:34:48.403+0000")
        }
    }, 
    "title" : "hhh.ro", 
    "url" : "sdfasdf"
}

This will only turn first level elements into an array, but nested document elements still remain MongoDB\Model\BSONDocument;

iterator_to_array doesn't work because this is not something iterable.

How do I convert entire document to an associative array like the old mongo driver or a stdClass?

2
May be you can try this json_decode(json_encode($result), true); - vijaykumar
It makes _id like this ["$oid"]=> string(24) "5784d428f079959a088b4595" - Alexandru R
You tried this $db->clients->findOne(array('_id' => $id))->toArray() - vijaykumar
that's for find. findOne doesn't return an iterator. And yes, I tried toArray. - Alexandru R

2 Answers

3
votes

you can set how the data is returned globally in database->setCollection options, Set typeMap to array

'typeMap' =>[
    'document' => 'array',
    'root' => 'array'
]

Link to Doc

1
votes

I couldn't find the setCollection suggested by @Delcon in PHP MongoDB library so I used the below method.

typeMap option can also be set in the options array inside findOne.

$someCollection->findOne(
[],
['typeMap' => ['root' => 'array', 'document' => 'array', 'array' => 'array']]
);

Link to Doc

edit:

You could also pass the options array to the connector to set it globally as described by this Stackoverflow post.

$options = ["typeMap" => ['root' => 'array', 'document' => 'array']];
$conn = new MongoDB\Client("mongodb://localhost:27017", [], $options);