Mongodb php get id of new document?
Asked Answered
B

4

36

Creating a document:

$db->collection->insert($content);
// $newDocID = ???

How to get the new document's id?

Braunstein answered 24/12, 2010 at 9:57 Comment(0)
S
62

According to the docs the array you pass to insert will be amended with an _id field:

$db->collection->insert($content);
$newDocID = $content['_id'];
Samarasamarang answered 24/12, 2010 at 10:38 Comment(2)
If 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...Faunia
Please note that this answer if for old legacy mongo driver. If you are looking for an answer for the new driver check this: https://mcmap.net/q/417900/-mongodb-php-get-id-of-new-documentKornegay
S
34

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:

  1. You don't need fsync flag like posted in comment by ZagNut in previous answer. So you don't need to wait for reply from DB.
  2. You don't need to actually insert anything to DB to get id. So you can prepare some related objects and then insert or not insert them - somewhat like transactions which mongo does not support (yet?).
  3. You actually can generate id in your application, not in db, So you can do whatever you want before or after insert.
Solace answered 13/7, 2012 at 9:18 Comment(6)
Disadvantage: This can have error E11000 duplicate key error index, if at same moment this function called from different clients.Highmuckamuck
@SomnathMuluk from my understanding, this is basically impossible. Every mongo id is a combination of timestamp, machine hostname and an incremental counter. If all clients have a unique hostname, how is this supposed to happen?Luettaluevano
@Luettaluevano Why would you assume you wouldn't have multiple clients on the same hostname? Although, based on the docs, the ID not only is based on the host, but the process, timestamp & an incremental counter, so even if the hostname is the same, and the timestamp is the same, the process & incremental counter parts should differ, so I'm also wondering how you would get the duplicate key error? The PHP docs state that the ID will be unique, so if there is collisions, that is a bug in PHP I would think.Linebacker
@Luettaluevano : I thought in same way. But I have received this error multiple times (1-2 times in week) when there are about 10k connections per minute.Highmuckamuck
@JoshRibakoff sorry, I forget to mention the process id (or rather the hash of it)Luettaluevano
@SomnathMuluk That's strange, how many processes / hosts are used in your setup?Luettaluevano
F
25

This works for me:

$insertResult = $collection->insertOne($object);
$id = $insertResult->getInsertedId();
Fencing answered 15/6, 2016 at 11:32 Comment(2)
This is the right thing to use if you got your driver through Composer.Vitellin
FYI. The getInsertedId method will return a \MongoDB\BSON\ObjectID instance. To get the actual Id value, cast to a string: (string)$insertResult->getInsertedId()Thermo
I
1
 $newDocument = $db->collection->findAndModify ( $row, $row, null, array('new'=>true,'upsert' => true));
 $strId = $newDocument['_id']->{'$id'};

http://php.net/manual/en/mongocollection.findandmodify.php

Insect answered 20/9, 2014 at 22:56 Comment(1)
Recommending 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.Linebacker

© 2022 - 2024 — McMap. All rights reserved.