Background
Recently I was writing a test kit with a bug-recording system, because I was using Django and MongoDB in the background, and I ran into a problem with how to implement a self added field.
The traditional relational database is very easy to implement, as long as directly set a self-added field on the line, the insertion of data without the value of this key, just do their own processing of the data on the line, will automatically achieve the function of the increase, but the relational database does not seem to have this function (or I do not know). After Baidu found all is MongoDB set method, is not what I want.
Solving ideas
Baidu did not find a good idea, it can only solve their own, my idea is very simple, the field will not increase, then make a self-increasing program.
I have found that there is a $inc method for modifying the MongoDB method. You can achieve a self increase of int type. Then it is very simple, build a collection, and then this collection only an int field, each time inserting data to this collection take ID on the line, and then call the $inc method, then realize the automatic self-increase scheme.
Code Show
Python is very simple to implement, and Python and Django fit perfectly. The code is as follows:
def bugplus (self): "" "
bugid self
: Return:true" ""
db = self.__choosecollection (config. collection[' BugID ']
db.update_one ({"BugID": Self.getbugid ()}, {"$inc": {"BugID": 1}}) return
True
After each insert succeeds, calling this method will enable the ID to be increased by itself.
def getbugid (self): ""
Gets the latest number for the current bug
: Return:none
"" "
db = self.__choosecollection (config. collection[' BugID ']
rst = Db.find_one () return
rst[' BugID ']
Call this method before inserting, so that the ID that is inserted each time the data is inserted is the ID that implements the increment.
Disadvantages
Of course, there are drawbacks to this approach, the invocation of the use of more methods, so you need to confirm the success of the method, or it will cause the next inserted ID is not the self-added data. One more method at a time can cause performance degradation.
Other
If there is a better way to achieve, please tell me!
The above Python+mongodb value of the simple realization is small series to share all the content, hope to give you a reference, but also hope that we support the cloud-dwelling community.