Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
like image 767
SomethingOn Avatar asked Oct 22 '11 17:10

SomethingOn


2 Answers

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);
like image 52
John Pancoast Avatar answered Sep 26 '22 22:09

John Pancoast


correct way is use ObjectId from MongoDB:

function getMongodbIDString($objectId){
    $objectId = new \MongoDB\BSON\ObjectId($objectId);
    return $objectId->jsonSerialize()['$oid'];
}

and do not cast the objectId like (string) $row['_id'] or $row->_id->{'$oid'}

like image 27
Rafael Guimarães Avatar answered Sep 24 '22 22:09

Rafael Guimarães