Skip to content

Instantly share code, notes, and snippets.

@pricco
Created August 1, 2012 14:12
Show Gist options
  • Save pricco/3227161 to your computer and use it in GitHub Desktop.
Save pricco/3227161 to your computer and use it in GitHub Desktop.
MongoKit: Auto Increment
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