代码如下:
public static function increament($tablename){
$coll = Yii::$app->mongodb->getCollection("ids");
$update = array('?inc'=>array('id'=>1));
$query = array('name'=>$tablename);
$command = array(
'findandmodify'=>'ids', 'update'=>$update,
'query'=>$query, 'new'=>true, 'upsert'=>true
);
$result = $coll->mongoCollection->db->command($command);
$id = $result['value']['id'];
$current_id = (int)$id->value;
Global $current_id;
return $current_id;
}
使用的时候直接 $dd = CID::increament(‘xxx’);即可获取到递增的id,
在一些场景,插入压力不是很多,但是很需要递增id的场景可以使用mongodb的这种递增id的方式,上面的写法是在yii2中使用的写法,如果不在yii2中使用mongodb的递增字段,则可以使用下面的代码:
function increament($m,$database_name,$collection_name){
$ids = "ids";
$db_name = "tracedb";
$db = $m->selectDB($db_name);
//$col = $m->selectDB($db_name)->$ids;
$query = array('name'=>$collection_name);
$update = array('$inc'=>array('id'=>1));
$result = $db->command(
array(
"findandmodify" => $ids,
"query" => $query,
"update" => $update,
'new'=>true,
'upsert'=>true
)
);
return $result['value']['id'];
}