coen-hyde / Shanty-Mongo

Shanty Mongo is a mongodb library for the Zend Framework. Its intention is to make working with mongodb documents as natural and as simple as possible. In particular allowing embedded documents to also have custom document classes.
Other
200 stars 52 forks source link

How to implement findAndModify operation with Shanty Mongo? #61

Closed valeeum closed 12 years ago

valeeum commented 12 years ago

I'm trying to recreate the following shell function using the Shanty Mongo library. Can anybody help point me in the right direction?

function counter(name) { var ret = db.counters.findAndModify({query:{_id:name}, update:{$inc : {next:1}}, "new":true, upsert:true}); return ret.next; }

I guess my real question is how can I execute a "findAndModify" operation?

tonymillion commented 12 years ago

Did you ever find a solution to this? I am interested in doing the same thing for a sequential operation collection.

valeeum commented 12 years ago

Yes, actually I did. The key was using native PHP Mongo driver to perform the operation:

<?php class Model_Mongo_Sequence extends Shanty_Mongo_Document { protected static $_collection = 'seq'; protected static $_requirements = array( 'collection' => 'Required', 'seq'=>'Required' );

public static function getNextID($collectionName)
{
    $seqObj = self::one(array("collection" => $collectionName));
    if(!$seqObj)
    {
        $seqModel = new self();
        $seqModel->collection = $collectionName;
        $startIndex = 0;
        $seqModel->seq = $startIndex;
        $seqModel->save();
    }

    //need to use native mongo driver for this fancy stuff
    $db = Shanty_Mongo::getWriteConnection()->selectDB(self::getDbName());
    $seq = $db->command(
        array(
            'findandmodify' => self::$_collection, 
            'query' => 
            array(
            'collection' => $collectionName
            ), 
        'update' => 
            array(
                '$inc' => 
                    array(
                        'seq' => 1
                    )
                ), 
                'new' => TRUE
            )
        );

    return $seq['value']['seq'];
}

}