Created
August 1, 2012 14:12
-
-
Save pricco/3227161 to your computer and use it in GitHub Desktop.
MongoKit: Auto Increment
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from mongokit import Document | |
class Sequential(Document): | |
__collection__ = 'sequential' | |
structure = { | |
'_id': basestring, | |
'next': long | |
} | |
indexes = [{ 'fields': ['_id'], 'unique': True }] | |
@classmethod | |
def reset(cls, db, type, start=1): | |
db.sequential.find_and_modify( | |
query={'_id': type}, | |
update={'next': long(start - 1)}, | |
upsert=True, | |
new=True) | |
@classmethod | |
def next(cls, db, type): | |
return db.sequential.find_and_modify( | |
query={'_id': type}, | |
update={'$inc': {'next': long(1)}}, | |
upsert=True, | |
new=True)['next'] | |
if __name__ == '__main__': | |
from mongokit import Connection | |
db = Connection(host='localhost', port=27017)['test'] | |
Sequential.reset(db, 'id', 1) #Optional | |
assert Sequential.next(db, 'id') == 1, 'Invalid sequential' | |
assert Sequential.next(db, 'id') == 2, 'Invalid sequential' | |
assert Sequential.next(db, 'id') == 3, 'Invalid sequential' | |
Sequential.reset(db, 'id', 2) | |
assert Sequential.next(db, 'id') == 2, 'Invalid sequential' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment