Home > php教程 > php手册 > body text

php实现Mongodb自定义方式生成自增ID的方法,mongodbid

WBOY
Release: 2016-06-13 09:09:58
Original
919 people have browsed it

php实现Mongodb自定义方式生成自增ID的方法,mongodbid

本文实例讲述了php实现Mongodb自定义方式生成自增ID的方法。分享给大家供大家参考。具体分析如下:
复制代码 代码如下://首先创建一个自动增长id集合 ids
>db.ids.save({name:"user", id:0});
//可以查看一下是否成功
> db.ids.find();
{ "_id" : ObjectId("4c637dbd900f00000000686c"), "name" : "user", "id" : 0 }
//然后每次添加新用户之前自增一下 ids集合 获得id
>userid = db.ids.findAndModify({update:{$inc:{'id':1}}, query:{"name":"user"}, new:true});
{ "_id" : ObjectId("4c637dbd900f00000000686c"), "name" : "user", "id" : 1 }
//注:因为findAndModify是一个方法完成更新查找两个操作,所以具有原子性,多线程不会冲突。
//然后保存相应的数据
>db.user.save({uid:userid.id, username:"kekeles", password:"kekeles", info:"http://www.bkjia.com/ "});
//查看结果
> db.user.find();
{ "_id" : ObjectId("4c637f79900f00000000686d"), "uid" : 1, "username" : "admin", "password" : "admin" }
//这是mongo的shell,如果用的是服务器端程序java php python,可以自己对这些操作封装一下,只用传几个参数就可以返回自增的id,还可以实现像Oracle的跨表的自增id。

自己写了一段php的,拿出来给大家分享。

<&#63;php
function mid($name, $db){
$update = array('$inc'=>array("id"=>1));
$query = array('name'=>$name);
$command = array(
'findandmodify'=>'ids', 'update'=>$update,
'query'=>$query, 'new'=>true, 'upsert'=>true
);
$id = $db->command($command);
return $id['value']['id'];
}
$conn = new Mongo();
$db = $conn->idtest;
$id = mid('user', $db);
$db->user->save(array(
'uid'=>$id, 
'username'=>'kekeles', 
'password'=>'kekeles',
 'info'=>'http://www.bkjia.com/ '
));
$conn->close();
&#63;>
Copy after login

希望本文所述对大家的php程序设计有所帮助。

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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template