Can Mongo IDs have the same value in different collections in the same database?
Although MongoDB does not support auto-increment sequence as a default feature like some relational databases, we can still achieve this functionality using a counter collection. The counter collection will have a single document that tracks the current unique identifier value.
Mongo ObjectIds are generated in a predictable manner, the 12-byte ObjectId value consists of: a 4-byte value representing the seconds since the Unix epoch, a 3-byte machine identifier, a 2-byte process id, and.
yes, the unique: true index guarantees it "in this one collection" - the algorithm "almost" guarantees it universally.
In MongoDB, each document stored in a collection requires a unique _id field that acts as a primary key. If an inserted document omits the _id field, the MongoDB driver automatically generates an ObjectId for the _id field. The 5 byte "random value" does not appear to be random.
The uniqueness constraint for _id is per collection, so yes - one and the same ID can occur once per Collection.
It's however very unlikely, if not impossible, for the same ID to be generated twice. So in order for this to happen you would have to manually insert duplicate IDs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With