標籤:
mongodb的自增實現根oracle,postgresql是差不多,都是通過計數器來實現的.
oracle自增實現: 執行個體說明oracle序列用法
postgresql自增實現: postgresql auto_increment 實現 通用方法
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); //插入資料
mongodb php auto increment 自增