mongodb php auto increment 自增

张映 发表于 2014-09-10

分类目录: nosql, php

标签:, , ,

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);   //插入数据


转载请注明
作者:海底苍鹰
地址:http://blog.51yip.com/php/1646.html