Home > Backend Development > PHP Tutorial > 在MongoDB中模拟Auto Increment的php代码_php技巧

在MongoDB中模拟Auto Increment的php代码_php技巧

WBOY
Release: 2016-05-17 09:20:58
Original
1014 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

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