MySQL users have most of the auto increment complex, but MongoDB default is not implemented, so need to simulate, programming language in PHP for example, the 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));
? >
Its implementation is mainly the use of MongoDB findandmodify command, as long as each MongoDB insert object before the creation of an ID assignment to the _id is OK, because its implementation to meet the atomicity, so there is no concurrency problem.
In addition, the findandmodify itself provides a upsert parameter, which is true to insert automatically, but that cannot customize the initial value, so the example in this article does not use Upsert.
BTW, the name of the database "_seq" begins with an underscore, so the list will be in front of you and easily distinguishable.
Reference: Auto Increment with MongoDB
After the MongoDB data file exceeds 2G, the write is super slow. Solution: Shard Fragmentation