Home >Backend Development >Python Tutorial >pymong implements self-increasing id
1. The solution provided by the official website
http://docs.mongodb.org/manual/tutorial/create-an-auto-incrementing-field/
Probably means creating a new table specifically to store the maximum userid. Each time an id is taken, it is +1, so there will be no duplication
2.pymongo implementation
The code is as follows. Note that the first time it returns {}, then 1-2-3...
Python code
print db.usercounter.find_and_modify({"_id": "users"}, update={ "$inc": {'count': 1}},upsert=True)
Just get the id Use it, and you don’t have to worry about multi-threading. However, it is a bit inconvenient to maintain two tables for one user table.
It’s almost enough, it’s not worth wasting too much time on one problem.
3. About the find_and_modify method:
http://api.mongodb.org/python/current/api/pymongo/collection.html
find_and_modify(query={}, update=None, upsert=False, sort=None, full_response=False, **kwargs)