Home > Database > Mysql Tutorial > mongodb php auto increment 自增

mongodb php auto increment 自增

WBOY
Release: 2016-06-07 16:39:20
Original
1340 people have browsed it

mongodb的自增实现根oracle,postgresql是差不多,都是通过计数器来实现的. oracle自增实现: 实例说明oracle序列用法 postgresql自增实现:? postgresql auto_increment 实现 通用方法 1,mongodb命令行下实现auto_increment db.counters.insert( //计数器表 { _

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" }
Copy after login

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);   //插入数据
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template