In Mongo/mongoid how to give sequential documents a numeric id?

168 Views Asked by At

I have 2 collections:

Categories

Posts

Each document in Posts belongs to exactly 1 Category (in mongoid, I have a has_many :Posts in Categories)

What I want to do is have a variable in Categories called post_count, and I also want to give each post a number from [1...post_count] so that if a post's number is 3, I know it's the 3rd post made within some category. In MySQL this would be pretty easy but in mongo I'm afraid I'll end up with duplicate post numbers and invalid post_count because it's not ACID.

I learned that for post_count I can just do this categoryObject.inc(:post_count, 1), and I think this will always be atomic and never wrong, but then after doing this, am I safe in assigning postObject.number = categoryObject.post_count?

I need it to work so even though if many people are doing a request to the server to create a post at the same time to the same category, that post_count will remain correct, and a post's number is always correct too.

0

There are 0 best solutions below