I'm trying to get the ID from mongodb to modify and delete user from a simple CRUD app with PHP and vue.js using axios
When I insert any user, I get this id.
{ "$oid": "5a8fd1ef1233610e40007667" }
I just need the ID that mongodb generate itself.
"5a8fd1ef1233610e40007667"
I'm using POST to get the ID and this is what I get when I use var_dump()
string(15) "[object Object]"
¿Any idea of how to get that ID? I've already tried several things, I hope you guys can help me
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.