Question

I'm trying to extract the hex code of a Mongo ID ObjectId using PHP. This error comes up whenever I try to extract the ID number and store it in another variable.

var_dumping the contents of a document fetched by a Mongo query gives something like the following:

object(MongoId)#242 (1) { ["$id"]=> string(24) "52795dc1613f4547710000df" } 

So to get that $id string, I do this:

$mongo = new MongoClient("mongodb://username:password@localhost/database");
$db = $mongo->selectDb("database");
$collection = $db->selectCollection("someCollection");
$doc = $collection->find( /* some query to get a document here */ )->getNext();

$recordId = $doc["_id"]['$id'];

And this gives the following error:

PHP Fatal error:  Cannot use object of type MongoId as array
Was it helpful?

Solution

The var_dump() of an MongoId is a bit missleading. The $doc["_id"] holds an object and not an array with a string, which you assume in your last line of code.

If you want the string representation of a MongoId just do this:

$recordId = (string) $doc["_id"];

or

$recordId = "{$doc['_id']}";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top