get mongodb _id object after upsert with php

后端 未结 6 1045
我寻月下人不归
我寻月下人不归 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条回答
  •  臣服心动
    2020-12-14 12:12

    Yes -- It is possible using a single query.

    MongoDB includes a findAndModify command that can atomically modify a document and return it (by default it actually returns the document before it's been modified).

    The PHP drivers don't include a convenient method for this on the collection class (yet -- check out this bug), but it can still be used (note that my PHP is terrible, so I may very well have made a syntax error in the following snippet):

    $key = array( 'something' => 'unique' );
    $data = array( '$inc' => array( 'someint' => 1 ) );
    $result = $mongodb->db->command( array(
        'findAndModify' => 'collection',
        'query' => $key,
        'update' => $data,
        'new' => true,        # To get back the document after the upsert
        'upsert' => true,
        'fields' => array( '_id' => 1 )   # Only return _id field
    ) );
    $id = $result['value']['_id'];
    

提交回复
热议问题