The code is roughly as follows:
Copy codeThe Code is as follows: <? Php
Function generate_auto_increment_id ($ namespace, array $ option = array ())
{
$ Option + = array (
'Init '=> 1,
'Step' => 1,
);
$ Instance = new Mongo ();
$ Instance = $ instance-> selectCollection ('_ seq', 'seq ');
$ Seq = $ instance-> db-> command (array (
'Findandmodify' => 'seq ',
'Query' => array ('_ id' => $ namespace ),
'Update' => array ('$ inc' => array ('id' => $ option ['step']),
'New' => true,
));
If (isset ($ seq ['value'] ['id']) {
Return $ seq ['value'] ['id'];
}
$ Instance-> insert (array (
'_ Id' => $ namespace,
'Id' => $ option ['init'],
));
Return $ option ['init '];
}
Var_dump (generate_auto_increment_id ('foo '));
Var_dump (generate_auto_increment_id ('bar', array ('init '=> 123 )));
?>
The specific implementation method is mainly to use the findAndModify command in MongoDB, as long as the ID value is generated before the insert object in MongoDB every time, it is OK, because its implementation meets the atomicity, therefore, there is no concurrency problem.
In addition, findAndModify provides an upsert parameter. If it is set to true, automatic insert can be performed, but the initial value cannot be customized. Therefore, the upsert is not used in the example in this article.
BTW: the name of the Database "_ seq" starts with an underscore (_ seq), which makes it easier to distinguish the list.
Reference: Auto Increment with MongoDB