'Why Mongo uses 12 Byte ObjectID?
Recently in an interview, I was asked this
"SQL supports auto increment of Primary Keys, where it occupies only the size that is required, i.e., 1 will use 1 bit, 20 will use 2 bits. So why does does MongoDB always use 12 Bytes for creating a ID? Why not use auto increment like SQL"?
Solution 1:[1]
Check this article
For instance, let’s say you are using an auto-incremental _id field in MongoDB then let’s see some of the possible considerations that you might have to make.
As you know, MongoDB is a distributed database and let’s say you are running your MongoDB instances on multiple servers then in that case you will have to ensure the auto-incrementing function is always assigning unique values for all writes that are happening on different servers.
What will happen when two users submitting create requests at around the same time. If you are setting up your own ID generator using a basic number, you would assign the same ID to both - causing a write conflict and either surfacing an error to the user that they couldn’t have controlled or causing your app to lag as it keeps submitting the same request until it finds an ID that works.
Are you planning to re-use those _id values for which you have deleted the corresponding documents. It might be the case when you are not retaining the data for a long time and doing a lot of deletes. In that case, you will have to keep track of the values which are available for re-use and subsequently you want to use an efficient data structure which does efficient push and pop of the data.
If your application is write intensive and let’s say a million documents is being inserted every minute or so then it would not be long before your auto-incremental id field will be 10-15 digits long.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | YuTing |