Joel
Joel

Reputation: 1639

Print MongoDB object _id in PHP

I am building a solution that uses a combination jQuery, PHP and MongoDB. I have a php query that returns an array that I would like to print_r to a web page. Everything works fine, expect I can not print the object _id, which looks like this.

$question_id = print_r($question->_id, true);
print_r($question_id);

stdClass Object ( [$oid] => 589625a3fef1fa3056501550 ) 

How can I convert this value to a string?

Upvotes: 2

Views: 3247

Answers (2)

Abhijeet Patil
Abhijeet Patil

Reputation: 418

For PHP 7 new MongoDB Driver

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

Upvotes: 0

Nicolás Pulido M
Nicolás Pulido M

Reputation: 83

With new mongodb PHP driver just cast as string the MongoDB\BSON\ObjectId object.

PHP object ref

example

print_r((string) $mongoObject->_id);

Upvotes: 4

Related Questions