Creating a document:
$db->collection->insert($content);
// $newDocID = ???
How to get the new document's id?
Creating a document:
$db->collection->insert($content);
// $newDocID = ???
How to get the new document's id?
According to the docs the array you pass to insert
will be amended with an _id
field:
$db->collection->insert($content);
$newDocID = $content['_id'];
You can also get _id before insert. Just add _id field to document with new MongoId ie.
$content['_id'] = new MongoId();
$db->collection->insert($content);
Also there are nice benefits of this:
E11000 duplicate key error index
, if at same moment this function called from different clients. –
Highmuckamuck This works for me:
$insertResult = $collection->insertOne($object);
$id = $insertResult->getInsertedId();
getInsertedId
method will return a \MongoDB\BSON\ObjectID
instance. To get the actual Id value, cast to a string: (string)$insertResult->getInsertedId()
–
Thermo $newDocument = $db->collection->findAndModify ( $row, $row, null, array('new'=>true,'upsert' => true));
$strId = $newDocument['_id']->{'$id'};
© 2022 - 2024 — McMap. All rights reserved.
fsync
option:$db->collection->insert($content, 'fsync' => \TRUE);
This ensures the "transaction" is completed first... – Faunia