Mongodb php get id of new document?
32,725
Solution 1
According to the docs the array you pass to insert
will be amended with an _id
field:
$db->collection->insert($content);
$newDocID = $content['_id'];
Solution 2
This works for me:
$insertResult = $collection->insertOne($object);
$id = $insertResult->getInsertedId();
Solution 3
$newDocument = $db->collection->findAndModify ( $row, $row, null, array('new'=>true,'upsert' => true));
$strId = $newDocument['_id']->{'$id'};
http://php.net/manual/en/mongocollection.findandmodify.php
Author by
Mark
Updated on June 16, 2020Comments
-
Mark almost 4 years
Creating a document:
$db->collection->insert($content); // $newDocID = ???
I'm trying to get the new document's id. How? Thanks.
-
ZagNut about 12 yearsIf you need the ID after the insert before you do another operation, you might also look at adding the
fsync
option:$db->collection->insert($content, 'fsync' => \TRUE);
This ensures the "transaction" is completed first... -
Josh Ribakoff over 8 yearsRecommending a findAndModify() w/ upsert & new flags sounds like it would work if running Mongo >= 3.x.x, but its an over complicated & less portable way to simply insert & get the ID, when insert() already does it.
-
Pila over 7 yearsThis saved my life!!
-
logicbloke over 7 yearsThis is the right thing to use if you got your driver through Composer.
-
Luke over 7 yearsFYI. The
getInsertedId
method will return a\MongoDB\BSON\ObjectID
instance. To get the actual Id value, cast to a string:(string)$insertResult->getInsertedId()
-
King Julien about 7 yearsPlease note that this answer if for old legacy mongo driver. If you are looking for an answer for the new driver check this: stackoverflow.com/a/37834261/352959