Most MySQL users have the AutoIncrement complex, but MongoDB is not implemented by default. Therefore, we need to simulate the following code in the programming language PHP:
The code is as follows:
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