I have variable $id="5fb3a0c67b5c000087002e60";
this is of type string in laravel & i want to convert this $id
to type ObjectId("5fb3a0c67b5c000087002e60")
.
when i fire query $result = $collection->find(['_id'=>$id]);
# so here $id is of type string and value inside '_id' which is from mongodb database is of type ObjectId, So to get result from this query $result = $collection->find(['_id'=>$id]);
I need to convert $id which is of string to ObjectId
My Answer:
In Laravel, you can use the MongoDB library to convert a string to an ObjectId. Here's how you can do it:
php
use MongoDB\BSON\ObjectId;
$id = "5fb3a0c67b5c000087002e60";
$objectId = new ObjectId($id);
$result = $collection->find(['_id' => $objectId]);
By creating a new `ObjectId` instance with the string value, you can convert it to the ObjectId type required for querying MongoDB.
Rate this post
4 of 5 based on 3444 votesComments