get mongodb _id object after upsert with php

后端 未结 6 1047
我寻月下人不归
我寻月下人不归 2020-12-14 11:56

is it possible to get the new/updated _id after the query? example code:

$key = array( \'something\' => \'unique\' );
$data = array( \'$inc\' => array(         


        
6条回答
  •  旧时难觅i
    2020-12-14 12:21

    I ran into this issue and worked around it by querying back the _id after the upsert. I thought I'd add some of my findings in case they're useful to anyone who comes here searching for info.

    When the upsert results in a new document being created in the collection, the returned object contains the _id (here's a print_r of an example):

    Array
    
    (
    
    [updatedExisting] => 0
    
    [upserted] => MongoId Object
        (
            [$id] => 506dc50614c11c6ebdbc39bc
        )
    
    [n] => 1
    [connectionId] => 275
    [fsyncFiles] => 7
    [err] => 
    [ok] => 1
    )
    

    You can get the _id from this:

    $id = (string)$obj['upserted'];
    

    However, if the upsert resulted in an existing document being updated then the returned object does not contain _id.

提交回复
热议问题