This article describes how to use php to generate a user-defined Mongodb ID. The example analyzes the implementation skills of Mongodb auto-increment fields and the corresponding php operation methods, for more information about how to use php to generate a user-defined ID for Mongodb, see the following example. 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.
<?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(array('uid'=>$id, 'username'=>'kekeles', 'password'=>'kekeles', 'info'=>'http://www.jb51.net/ '));$conn->close();?>
I hope this article will help you with php programming.