Reputation: 707
Lets consider an example of blog site where I want to save questions and replies in two different documents. I know this can also be done with Embedding
documents but lets assume we want two different documents.
And I have Like
option on both question and reply. If user likes a question that particular question's objectID
is stored inside a Like
document and similarly for likes in reply.
Now I wonder whether the objectID's
that I store in Like
documents could create a conflict. Like if the question's objectid
is same
as any reply's objectid
. IS it possible to have such conflicts??
In Mongodb ObjectID
documentation the following is provided:
ObjectId is a 12-byte BSON type, constructed using:
a 4-byte value representing the seconds since the Unix epoch,
a 3-bytemachine identifier,
a 2-byte process id, and
a 3-byte counter, starting with a random value.
Upvotes: 3
Views: 1471
Reputation: 20712
It is unique for all practical purposes. The non- uniqueness mentioned is a rather theoretical one.
The ObjectId is constructed out of
So, at median, unless you write in excess of 3080 documents per second per client, you should be safe.
It is to note that _id
has an unique constraint: Even if you'd try to write the same ObjectId twice, there'd be an exception.
Side note: even hash algorithms like MD5 or (to a lesser extent) SHA256 have a slight chance of collision. But with a unique constraint, you are safe.
Edit: Since an exception is thrown in the very, Very, VERY rare case that two identical ObjectIds are generated and tried to be written concurrently, you simply handle them by generating a new ObjectId and try to save the document again.
Upvotes: 4