pymong implements self-increasing id

巴扎黑
Release: 2016-12-09 09:46:11
Original
2071 people have browsed it

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)

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template