This article describes the example of php's method to implement Mongodb's custom method to generate self-increasing ID. Share it with everyone for your reference. The specific analysis is as follows:
Copy code The code 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.bkjia.com/ "});
//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.
<?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(); ?>
I hope this article will be helpful to everyone’s PHP programming design.