get mongodb _id object after upsert with php

Toby picture Toby · Dec 13, 2010 · Viewed 12.8k times · Source

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

$key = array( 'something' => 'unique' );
$data = array( '$inc' => array( 'someint' => 1 ) );
$mongodb->db->collection->update( $key, $data, array( 'upsert' => true ) );

$key is not holding the new/old _id object and i assume that $data will not either because its just an instruction.

Answer

Cameron picture Cameron · Dec 14, 2010

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'];