Simulate the PHP code for Auto Increment in MongoDB

  • 2020-03-31 21:35:10
  • OfStack

The code looks like this:
 
<?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))); 
?> 

Its concrete implementation method is mainly used in directing (link: http://www.mongodb.org/display/DOCS/findAndModify+Command) command, as long as before each insert into the mongo object generated ID assigned to _id with respect to OK, because its implementation meet atomicity, so there is no concurrency issues.

Also, findAndModify itself provides an upsert parameter that can be automatically inserted if true, but you can't customize the initial value, so the example doesn't use upsert.

BTW, the name of database "_seq" begins with an underscore, so that the list comes first and is easier to identify.

Reference: (link: http://shiflett.org/blog/2010/jul/auto-increment-with-mongodb)


Related articles: