How does PHP implement MongoDB custom build self-increment ID? This paper mainly introduces the method of generating self-increment ID in the way of realizing MongoDB custom in PHP, and the implementation and corresponding PHP method of MongoDB self-increment field are analyzed in the example. We hope to help you.
The example in this paper describes how to generate a self-increment ID by implementing the MongoDB customization method in PHP. Share to everyone for your reference. The specific analysis is as follows:
First create an auto-Grow ID collection ids>db.ids.save ({name: "User", id:0});//You can see if it is successful > Db.ids.find (); {"_id": ObjectId ("4c637dbd900f00000000686c"), "name": "User", "id": 0}//then add the IDs collection to get Id>userid = Db.ids before each new user is added . findandmodify ({update:{$inc: {' id ': 1}}, query:{"name": "User"}, new:true}); {"_id": ObjectId ("4c637dbd900f00000000686c"), "name": "User", "id": 1}//Note: Because Findandmodify is a method to complete an update to find two operations, it is atomic, Multithreading does 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 shell of MONGO, if is the server-side program Java PHP python, you can encapsulate these operations, only a few parameters can return the self-increment ID, but also to achieve a cross-table like Oracle self-increment ID.
I wrote a piece of PHP, take it out for everyone to share.
<?phpfunction 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 (' uid ' = ' $id, ' username ' = ' kekeles ', ' password ' = ' kekeles ', ' info ' = ' http://www.jb51.net/'); $conn->close ();? >
Related recommendations:
PHP MongoDB Gridfs How to store files
PHP MongoDB Operation class with a few simple examples
Parsing: Things to keep in mind when using PHP MongoDB extensions _php Tutorial