3

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

1 Answer 1

13

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']}";
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.