PHP code to simulate Auto Increment in MongoDB_PHP tutorial

WBOY
Release: 2016-07-21 15:31:15
Original
730 people have browsed it

代码大致如下所示:

复制代码 代码如下:

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)));
?>

其具体实现方式主要是利用MongoDB中findAndModify命令,只要每次往MongoDB里insert对象前生成ID赋值给_id就OK了,因为它的实现满足原子性,所以不存在并发问题。

另外说明一点,findAndModify本身提供了一个upsert参数,为true的话可以自动insert,但那样就不能自定义初始值了,所以文中示例没有使用upsert。

BTW,数据库“_seq”的名字以下划线开头,这样列表的时候会排在前面,更容易分辨些。

参考:Auto Increment with MongoDB

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/323090.htmlTechArticle代码大致如下所示: 复制代码 代码如下: ?php function generate_auto_increment_id($namespace, array $option = array()) { $option += array( 'init' = 1, 'step' = 1, ); $...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template