Php implements the Mongodb custom method to generate the auto-increment ID
This article describes how to generate a user-defined Mongodb ID using php. The example analyzes the implementation skills of Mongodb auto-increment fields and the corresponding php operation methods. For more information, see
This example describes how to generate a user-defined ID for Mongodb in php. Share it with you for your reference. The specific analysis is as follows:
The Code is as follows:
// First create an auto-increment id set ids
> Db. ids. save ({name: "user", id: 0 });
// Check whether the operation is successful.
> Db. ids. find ();
{"_ Id": ObjectId ("4c637dbd900f00000000686c"), "name": "user", "id": 0}
// Then, the ids are automatically added to the ids set each time a new user is added.
> 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 the update and search operations, it is atomic and does not conflict with multithreading.
// Save the corresponding data
> Db. user. save ({uid: userid. id, username: "kekeles", password: "kekeles", info: "http://www.jb51.net /"});
// View the result
> Db. user. find ();
{"_ Id": ObjectId ("4c637f79900f00000000686d"), "uid": 1, "username": "admin", "password": "admin "}
// This is the mongo shell. If you use the server-side java php python program, you can encapsulate these operations by yourself. Only a few parameters are required to return the auto-increment id, you can also implement auto-increment IDs across tables like Oracle.
I wrote a php article and shared it with you.
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<? Php Function mid ($ name, $ db ){ $ Update = array ('$ inc' => array ("id" => 1 )); $ Query = array ('name' => $ name ); $ Command = array ( 'Findandmodify' => 'kids', '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 help you with php programming.