[php]代码库
function getNextId($mongo,$name,$param=array()){
$param += array( //默认ID从1开始,间隔是1
'init' => 1,
'step' => 1,
);
$update = array('$inc'=>array('id'=>$param['step'])); //设置间隔
$query = array('name'=>$name);
$command = array(
'findandmodify' => 'ids',
'update' => $update,
'query' => $query,
'new' => true
);
$id = $mongo->db->command($command);
if (isset($id['value']['id'])) {
return $id['value']['id'];
}else{
$mongo->insert(array(
'name' => $name,
'id' => $param['init'], //设置ID起始数值
));
return $param['init'];
}
}
$mongo = new Mongo();
$curDB = $mongo->selectCollection('test', 'ids'); //test库中的ids表
$user = $mongo->selectCollection('test', 'users'); //test库中的users表
$id = getNextId($curDB,'userid',array('init'=>10000,'step'=>2)); //取得下一条数据的ID
$obj = array("_id"=>$id,"name"=>"tankzhang");
$user->insert($obj); //插入数据