The example in this article describes how PHP implements Mongodb’s custom method to generate self-increasing IDs. Share it with everyone for your reference. The specific analysis is as follows:
//First create an automatically growing id collection ids
>db.ids.save({name:"user", id:0});
//You can check whether it is successful
> db.ids.find();
{ "_id" : ObjectId("4c637dbd900f00000000686c"), "name" : "user", "id" : 0 }
//Then each time before adding a new user, increase the ids collection and get the id
>userid = db.ids.findAndModify({update:{$inc:{'id':1}}, query:{"name":"user"}, new:true});
{ "_id" : ObjectId("4c637dbd900f00000000686c"), "name" : "user", "id" : 1 }
//Note: Because findAndModify is a method that completes two operations of update and search, it is atomic and multi-threading will not conflict.
//Then save the corresponding data
>db.user.save({uid:userid.id, username:"kekeles", password:"kekeles", info:"http://www.jb51.net/ "});
//View results
> db.user.find();
{ "_id" : ObjectId("4c637f79900f00000000686d"), "uid" : 1, "username" : "admin", "password" : "admin" }
//This is the mongo shell. If you are using the server-side program java php python, you can encapsulate these operations yourself. You only need to pass a few parameters to return the auto-incremented id, and you can also implement cross-table processing like Oracle's Auto-increment id.
I wrote a piece of php myself and shared it with everyone.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
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.jb51.net/ '
));
$conn->close();
?>
|
1
2
3
4
5
6
7
8
9
10
11
12
13
15
16
17
18
19
20
21
22
|
<🎜>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.jb51.net/ '
));
$conn->close();
?>
|
I hope this article will be helpful to everyone’s PHP programming design.
http://www.bkjia.com/PHPjc/973137.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/973137.htmlTechArticleHow to generate self-increasing ID in Mongodb customization using PHP. This article mainly introduces the customization method in Mongodb in PHP. The method of generating auto-increment ID, an example analysis of the implementation technology of Mongodb auto-increment field...