Get ObjectId MongoDB via PHP [closed]

2020-06-06 08:07发布

问题:

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 7 years ago.

Here's my script

$terms = ['username' => $uri];
$user = $collection->findOne($terms);

result

array (size=4)
  '_id' => 
    object(MongoId)[29]
      public '$id' => string '4ff6e96bb0b4599016000006' (length=24)
  'username' => string 'me' (length=10)
  'name' => string 'Yes, It's me!' (length=16)

Get Name

$name = $user['name'];

But, how can i get $user['_id'] ?

I try $user['_id'] NOT WORK

Please help. Thanks

UPDATE

Problem solved with $user['_id']->{'$id'}

回答1:

$user['_id']->{'$id'} is not necessary and ugly, you can simply cast it to string to get id $id = (string)$user['_id'];