How do you get the string value of a MongoID using PHP?

SomethingOn picture SomethingOn · Oct 22, 2011 · Viewed 21.3k times · Source

After doing an insert I want to pass the object to the client using json_encode(). The problem is, the _id value is not included.

$widget = array('text' => 'Some text');

$this->mongo->db->insert($widget);


If I echo $widget['_id'] the string value gets displays on the screen, but I want to do something like this:

$widget['widgetId'] = $widget['_id']->id;


So I can do json_encode() and include the widget id:

echo json_encode($widget);

Answer

John Pancoast picture John Pancoast · Oct 28, 2011

Believe this is what you're after.

$widget['_id']->{'$id'};

Something like this.

$widget = array('text' => 'Some text');
$this->mongo->db->insert($widget);
$widget['widgetId'] = $widget['_id']->{'$id'};
echo json_encode($widget);