Home >Backend Development >PHP Tutorial >monde PHP code to simulate Auto Increment in MongoDB
The code roughly looks like this:
Copy code 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 is generated and assigned to _id each time before inserting the object in MongoDB, it will be OK. Because its implementation satisfies atomicity, there is no concurrency problem.
In addition, findAndModify itself provides an upsert parameter. If it is true, it can be automatically inserted, but then the initial value cannot be customized, so the example in the article does not use upsert.
BTW, the name of the database "_seq" starts with an underscore, so that it will be listed first and easier to distinguish.
Reference: Auto Increment with MongoDB
The above introduces the PHP code for monde to simulate Auto Increment in MongoDB, including the content of monde. I hope it will be helpful to friends who are interested in PHP tutorials.