12

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);
Shakti Singh
  • 84,385
  • 21
  • 134
  • 153
SomethingOn
  • 9,813
  • 17
  • 68
  • 107

5 Answers5

45

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);
John Pancoast
  • 1,241
  • 16
  • 14
  • 2
    Reference here: http://php.net/manual/en/class.mongoid.php. I'd prefer the (string) typecast below myself but at the time of the question I was using the method outlined in the docs. – John Pancoast Nov 18 '14 at 21:27
23

You can also use:

(string)$widget['_id']
meltix
  • 311
  • 3
  • 4
5

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'}

2

I used something similar:

(string)$widget->_id
Ikhlak S.
  • 8,578
  • 10
  • 57
  • 77
Abilash
  • 21
  • 6
  • Thanks a lot :) it is working fine for me... $filter=['_id' => $row->_id]; and $filter you can pass to deleteOne and findOne function – Venkatgreat309 Mar 11 '20 at 14:51
1

I used something similar if object:

$widget->_id->{'$oid'}

or

(string)$widget->_id

or array :

$widget['id']->{'$oid'}
(string)$widget['_id']