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

5

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);
Churchless answered 22/10, 2011 at 17:27 Comment(0)
M
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);
Melodrama answered 28/10, 2011 at 6:36 Comment(1)
Reference here: 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.Melodrama
J
23

You can also use:

(string)$widget['_id']
Jaguarundi answered 14/1, 2013 at 20:16 Comment(0)
P
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'}

Pandit answered 25/9, 2019 at 18:4 Comment(2)
thanks for giving this code. no other code works except this...once thanks alot.Heddi
@Dhanunjaya, nice, try use Doctrine ODM, it handle all this stuffChema
M
2

I used something similar:

(string)$widget->_id
Maryannemarybella answered 9/7, 2013 at 11:59 Comment(1)
Thanks a lot :) it is working fine for me... $filter=['_id' => $row->_id]; and $filter you can pass to deleteOne and findOne functionAubrette
F
1

I used something similar if object:

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

or

(string)$widget->_id

or array :

$widget['id']->{'$oid'}
(string)$widget['_id']
Faustofaustus answered 6/2, 2018 at 9:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.