Home  >  Article  >  Backend Development  >  pymong implements self-increasing id

pymong implements self-increasing id

巴扎黑
巴扎黑Original
2016-12-09 09:46:112029browse

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)

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:python bind functionNext article:python bind function