Closed valeeum closed 12 years ago
Did you ever find a solution to this? I am interested in doing the same thing for a sequential operation collection.
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'];
}
}
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?