Simulate AutoIncrement php code in MongoDB

Source: Internet
Author: User
Most MySQL users have the AutoIncrement complex, but MongoDB is not implemented by default, so we need to simulate it. the programming language uses PHP as an example for MongoDB.

The code is roughly as follows:
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

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.