Mongodb's auto-increment implementation is similar to that of the root oracle database. postgresql is implemented through counters. oracle Auto-increment implementation: the instance describes oracle sequence usage: postgresql auto-increment implementation :? Postgresqlauto_increment: common method 1. auto_incrementdb.counters.insert (counter table {_
Mongodb's auto-increment implementation is similar to that of the root oracle database. postgresql is implemented through counters. oracle Auto-increment implementation: the instance describes oracle sequence usage: postgresql auto-increment implementation :? Postgresql auto_increment implements common method 1, and auto_increment db. counters. insert (// counter table {_
Mongodb's auto-incrementing Implementation of root oracle, postgresql is similar, all implemented through counters.
Oracle Auto-increment implementation:Instance description oracle sequence usage
Postgresql auto-increment implementation :?Postgresql auto_increment
1. Implement auto_increment under the mongodb command line
> Db. counters. insert (// counter table {_ id: "userid", seq: 0}); WriteResult ({"nInserted": 1})> db. counters. find (); {"_ id": "userid", "seq": 0}> function getNextSequence (name) {// remove the ID function var ret = db. counters. findAndModify ({query: {_ id: name}, update: {$ inc: {seq: 1}, // seq is the seq Field new: true in the counters table above, upsert: true}); return ret. seq ;};> db. users. insert (// insert data {_ id: getNextSequence ("userid"), name: "tank"}); WriteResult ({"nInserted": 1})> db. users. find (); // view {"_ 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 implements auto_increment
Function getNextId ($ mongo, $ name, $ param = array () {$ param + = array (// The default ID starts from 1, the interval is 1 'init '=> 1, 'step' => 1 ,); $ update = array ('$ inc' => array ('id' => $ param ['step']); // set the interval $ query = array ('name' => $ name); $ command = array ('findandmodify '=> 'kids', '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 '], // set the start value of the id )); return $ param ['init ']; }}$ mongo = new Mongo (); $ curDB = $ mongo-> selectCollection ('test', 'id '); // ids table $ user = $ mongo-> selectCollection ('test', 'users') in the test database; // users table $ id = getNextId ($ curDB, 'userid', array ('init '=> 10000, 'step' => 2 )); // obtain the ID of the next data $ obj = array ("_ id" => $ id, "name" => "tankzhang "); $ user-> insert ($ obj); // insert data
Original article address: mongodb php auto increment auto-increment. Thank you for sharing it with the original author.