当前位置:Gxlcms > mysql > mongodbphpautoincrement自增

mongodbphpautoincrement自增

时间:2021-07-01 10:21:17 帮助过:64人阅读

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

  1. > db.counters.insert( //计数器表
  2. {
  3. _id: "userid",
  4. seq: 0
  5. }
  6. );
  7. WriteResult({ "nInserted" : 1 })
  8. > db.counters.find();
  9. { "_id" : "userid", "seq" : 0 }
  10. > function getNextSequence(name) { //取下个ID的函数
  11. var ret = db.counters.findAndModify(
  12. {
  13. query: { _id: name },
  14. update: { $inc: { seq: 1 } }, //这里seq就是上面counters表中的seq字段
  15. new: true,
  16. upsert: true
  17. }
  18. );
  19. return ret.seq;
  20. };
  21. > db.users.insert( //插入数据
  22. {
  23. _id: getNextSequence("userid"),
  24. name: "tank"
  25. }
  26. );
  27. WriteResult({ "nInserted" : 1 })
  28. > db.users.find(); //查看
  29. { "_id" : 1, "name" : "tank" }
  30. > db.users.insert(
  31. {
  32. _id: getNextSequence("userid"),
  33. name: "test"
  34. }
  35. );
  36. WriteResult({ "nInserted" : 1 })
  37. > db.users.find();
  38. { "_id" : 1, "name" : "tank" }
  39. { "_id" : 2, "name" : "test" }

2,php实现auto_increment

  1. function getNextId($mongo,$name,$param=array()){
  2. $param += array( //默认ID从1开始,间隔是1
  3. 'init' => 1,
  4. 'step' => 1,
  5. );
  6. $update = array('$inc'=>array('id'=>$param['step'])); //设置间隔
  7. $query = array('name'=>$name);
  8. $command = array(
  9. 'findandmodify' => 'ids',
  10. 'update' => $update,
  11. 'query' => $query,
  12. 'new' => true
  13. );
  14. $id = $mongo->db->command($command);
  15. if (isset($id['value']['id'])) {
  16. return $id['value']['id'];
  17. }else{
  18. $mongo->insert(array(
  19. 'name' => $name,
  20. 'id' => $param['init'], //设置ID起始数值
  21. ));
  22. return $param['init'];
  23. }
  24. }
  25. $mongo = new Mongo();
  26. $curDB = $mongo->selectCollection('test', 'ids'); //test库中的ids表
  27. $user = $mongo->selectCollection('test', 'users'); //test库中的users表
  28. $id = getNextId($curDB,'userid',array('init'=>10000,'step'=>2)); //取得下一条数据的ID
  29. $obj = array("_id"=>$id,"name"=>"tankzhang");
  30. $user->insert($obj); //插入数据

人气教程排行