2👍
See the The MongoDB\BSON\ObjectId class.
In MongoDB, each document stored in a collection requires a unique _id field that acts as a primary key. If an inserted document omits the _id field, the driver automatically generates an ObjectId for the _id field.
specifically MongoDB\BSON\ObjectId::__toString
, which returns the hexidecimal representation of the ObjectId. You can invoke __toString
by casting the ObjectId to string, for example:
$stringID = (string)$objectID;
You do not need to create the ObjectID when you insert the record, for example (based on your comment)
$bulk = new MongoDB\Driver\BulkWrite();
$doc = [ 'firstname' => $firstname, 'lastname' => $lastname ];
$bulk->insert($doc);
$result = $manager->executeBulkWrite('db.collection', $bulk);
var_dump($result);
The mongo driver will create and set the ‘_id’ field, insert
takes the array by reference and can alter it.
Source:stackexchange.com