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

Share:
32,725
Mark
Author by

Mark

Updated on June 16, 2020

Comments

  • Mark
    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
    ZagNut about 12 years
    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...
  • Josh Ribakoff
    Josh Ribakoff over 8 years
    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.
  • Pila
    Pila over 7 years
    This saved my life!!
  • logicbloke
    logicbloke over 7 years
    This is the right thing to use if you got your driver through Composer.
  • Luke
    Luke over 7 years
    FYI. 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
    King Julien about 7 years
    Please 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