MongoDB and Auto Increment
Chris Shiflett shares a solution to emulate the MySQL auto_increment with MongoDB. While you should read his post, the proposed solution is:
db.seq.findAndModify({ query: {"_id":"users"}, update: {$inc: {"seq":1}}, new: true });
Kenny Gorman warns that the above solution is not exactly optimal:
When using this technique each insert would require both the insert as well as the findAndModify command which is a query plus an update. So now you have to perform 3 operations where it used to be one. Not only that, but there are 3 more logical I/O’s due to the query, and those might be physical I/O’s. This pattern is easily seen with the mongostat utility.
I remember Twitter has tried to solve a similar problem — probably at a different, larger scale — and they came up with Snowflake:
We needed something that could generate tens of thousands of ids per second in a highly available manner. This naturally led us to choose an uncoordinated approach. These ids need to be roughly sortable, meaning that if tweets A and B are posted around the same time, they should have ids in close proximity to one another since this is how we and most Twitter clients sort tweets.
If you have other ideas (even if not directly related to MongoDB) I’d love to hear them!
Original title and link for this post: MongoDB and Auto Increment (published on the NoSQL blog: myNoSQL)