Insert JSON into MongoDb directly from PHP

The PHP MongDB Driver accepts arrays for inserts and queries (see here: http://www.php.net/manual/en/mongo.queries.php)

So you need to convert your JSON to an array.

Luckily, in general this is quite easy ... here is a snippet from a longer piece of code (see this article) to insert JSON data from the Twitter API into an array, then into MongoDB:

// Convert JSON to a PHP array
$usertimeline = json_decode($usertimeline);

// Loop array and create seperate documents for each tweet
foreach ($usertimeline as $id => $item) {
   $collection->insert($item);
}

Note the json_decode() function can convert to an array by passing true as the second parameter.


Here's a tip for others who want to do this, but want to update records rather than insert new ones. In order to get Justin's approach to work, I had to make sure that I convert the _id object for each item to a MongoId:

// Convert JSON to a PHP array
$usertimeline = json_decode($usertimeline);

// Loop array and create seperate documents for each tweet
foreach ($usertimeline as $id => $item) {
   $mongo_id = new MongoId($id);
   $item->_id = $mongo_id;
   $collection->update(array('_id' => $mongo_id), $item);
}

Tags:

Php

Json

Mongodb