Simulate the PHP code _php technique of auto increment in MongoDB

Source: Internet
Author: User
Tags mongodb
The code is roughly as follows:
Copy Code code 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 that the list will be in front of you and be easier to distinguish.

Reference: Auto Increment with MongoDB

-->
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.