Mongodb php get id of new document?
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:
- You don't need fsync flag like posted in comment by ZagNut inprevious answer. So you don't need to wait for reply from DB.
- You don't need to actually insert anything to DB to get id. So you canprepare some related objects and then insert or not insert them -somewhat like transactions which mongo does not support (yet?).
- You actually can generate id in your application, not in db, So you cando whatever you want before or after insert.
This works for me:
$insertResult = $collection->insertOne($object);$id = $insertResult->getInsertedId();