Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autoincrement with MongoEngine

I'm developing a blog engine with Flask and MongoEngine, and I need sequential IDs for my posts.

I need MongoEngine to create a new ID for each new post, so I was thinking of doing something like this:

class Post(Document):
  title = StringField(required=True)
  content = StringField(required=True)
  published_at = datetime.utcnow()
  id = Post.objects.count() + 1

Will this work? is there a better way to do this?

like image 625
Mahmoud Hanafy Avatar asked May 11 '26 19:05

Mahmoud Hanafy


2 Answers

Firstly, you need to understand why you need incremental id's? What do they solve?

Theres no native solution in mongoDB - please read: http://www.mongodb.org/display/DOCS/How+to+Make+an+Auto+Incrementing+Field

As you already have a unique identifier with the pk of the Post, why not use that?

Finally, if I haven't dissuaded you from folly, there is a SequenceField in mongoengine that handles incrementing for you.

like image 75
Ross Avatar answered May 14 '26 08:05

Ross


Edit: This is an incorrect solution, as others pointed out that this approach causes a race condition. I have only left it here so others would know why this is bad. (multiple clients can access this same object and increment it, resulting in inconsistent results).


Old answer:

I figured it out.

The Post class looks like this:

class Post(Document):
      title = StringField(required=True)
      content = StringField(required=True)
      published_at = datetime.utcnow()
      ID = IntField(min_value=1)

And in the function that inserts the post, I count the available records and then increment them by 1, like so:

def create_post(title, content):
      Post(title=title, content=content, ID=Post.objects.count() + 1).save()
like image 39
Mahmoud Hanafy Avatar answered May 14 '26 08:05

Mahmoud Hanafy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!