Convert Mongo BSONDocument to an array in PHP

Josh Sherman
1 min read
Software Development PHP NoSQL

Ran into a scenario this weekend where I needed to take a sub-document from Mongo but I needed it in an array in PHP. Reading the data from Mongo with PHP was simple and won’t be discussed. What I’d like to talk about is taking the BSONDocument that Mongo returns and converting it into an array.

I did a bit of searching and most solutions involved iterating through the BSONDocument and creating an array from that. Iterating… wait, iterators are what does that. I have an idea!!

As of PHP 5.1 you can use the iterator_to_array function. You can pass it an iterator (like an ArrayIterator) and it will spit back an array. Optionally you can pass a second argument of false and get an array instead of an associative array (which is the default).

The function’s first argument is supposed to be a traversable interface. I wasn’t entirely sure if that’s what I was working with but figured what the hell. Turns out the BSONDocument was a traversable interface so in return I received an associative array based on the BSONDocument I passed in.

Not much to the code either:

$record  = $mongo->collection->findOne([ 'what' => 'iwaslookingfor' ]);
$sub_doc = iterator_to_array($record['subDoc']);

If you need to to grab multiple records, which will return a cursor instead of a document, you will need to do a little extra work:

$records = $mongo->collection->find([ 'what' => 'iwaslookingfor' ]);
$records = iterator_to_array($records);

    function (&$record)
      if (isset($record['subDoc'])) {
        $record['subDoc'] = iterator_to_array($record['subDoc']);

Now every subDoc (if present) will be converted to an array!

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.

Currently Reading

Parasie Eve

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles