Mongodb auto-incrementing to implement the root oracle, postgresql is similar, all implemented through counters
1. Implement auto_increment under the mongodb command line
The code is as follows: |
Copy code |
> 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 in the counters table above. New: true, 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
The code is as follows: |
Copy code |
Function getNextId ($ mongo, $ name, $ param = array ()){ $ Param + = array (// The default ID starts from 1 and 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 '], // sets the start value of the id. )); Return $ param ['init ']; } } $ Mongo = new Mongo (); $ CurDB = $ mongo-> selectCollection ('test', 'id'); // ids table in the test Database $ User = $ mongo-> selectCollection ('test', 'users'); // users table in the test Database $ 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 |