This article describes the way PHP implements MongoDB customization to generate the self-increasing ID. Share to everyone for your reference. The specific analysis is as follows:
Copy Code code as follows:
First create an automatic growth ID collection IDs
>db.ids.save ({name: "User", id:0});
You can see if it's successful.
> Db.ids.find ();
{"_id": ObjectId ("4c637dbd900f00000000686c"), "name": "User", "id": 0}
And then add the IDs collection to get the IDs each time before adding new users
>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 lookup for two operations, it is atomic and multithreading does not conflict.
And then save the appropriate 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 the MONGO, if you are using the server-side Java PHP python, you can encapsulate these operations, using only a few parameters to return the ID, you can also implement a cross table like Oracle ID.
I wrote a section of PHP, take out to share.
<?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.jb51.net/')
);
$conn->close ();
? >
I hope this article will help you with your PHP program design.