mongodb的自增實現根oracle,postgresql是差不多,都是通過計數器來實現的
1,mongodb命令列下實現auto_increment
代碼如下 |
複製代碼 |
> db.counters.insert( //計數器表 { _id: "userid", seq: 0 } ); WriteResult({ "nInserted" : 1 }) > db.counters.find(); { "_id" : "userid", "seq" : 0 } > function getNextSequence(name) { //取下個ID的函數 var ret = db.counters.findAndModify( { query: { _id: name }, update: { $inc: { seq: 1 } }, //這裡seq就是上面counters表中的seq欄位 new: true, upsert: true } ); return ret.seq; }; > db.users.insert( //插入資料 { _id: getNextSequence("userid"), name: "tank" } ); WriteResult({ "nInserted" : 1 }) > db.users.find(); //查看 { "_id" : 1, "name" : "tank" } > db.users.insert( { _id: getNextSequence("userid"), name: "test" } ); WriteResult({ "nInserted" : 1 }) > db.users.find(); { "_id" : 1, "name" : "tank" } { "_id" : 2, "name" : "test" }
|
2,php實現auto_increment
代碼如下 |
複製代碼 |
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); //插入資料 |