Reputation: 33571
Creating a document:
$db->collection->insert($content);
// $newDocID = ???
How to get the new document's id?
Upvotes: 36
Views: 34950
Reputation: 339
This works for me:
$insertResult = $collection->insertOne($object);
$id = $insertResult->getInsertedId();
Upvotes: 25
Reputation: 130
$newDocument = $db->collection->findAndModify ( $row, $row, null, array('new'=>true,'upsert' => true));
$strId = $newDocument['_id']->{'$id'};
http://php.net/manual/en/mongocollection.findandmodify.php
Upvotes: 1
Reputation:
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:
Upvotes: 34