Reputation: 3874
Is MongoDB _id unique by default, or do I have to set it to unique?
Upvotes: 24
Views: 14863
Reputation: 2836
For the most part, _id in mongodb is unique enough. There is one edge case where it's possible to generate a duplicate id though:
If you generate more than (2^(3 * 8))-1 = 16,777,215 object ids in the same single second, you could get a duplicate id due to how object ids are generated, otherwise you are alright. If you did generate that many ids in the same second, you are in a lottery and have a 1 in 2^(5 * 8) chance on top of this to get your duplicate id.
Let me know if you ever manage to pull this off with a realistic use case. Apparently google only gets around 70,000 searches a second.
Here is my source: https://www.mongodb.com/blog/post/generating-globally-unique-identifiers-for-use-with-mongodb
ObjectID is a 96-bit number which is composed as follows:
Update: I have also heard the 5-byte random value could instead be replaced by 3 bytes representing the machine id and 2 bytes representing the process id.
Upvotes: 28
Reputation: 2888
Share what I learned about this topic here:
Different from other RDBMS, Mongodb document's Id is generated on the client side. This functionality is usually implemented in the drivers of various programming languages.
The Id is string with 12 bytes length, which consists of several parts as follows:
TimeStamp(4 bytes) + MachineId(3 bytes) + ProcessId(2 bytes) + Counter(3 bytes)
Based on this pattern, it's extremely unlikely to have two Ids duplicated.
Upvotes: 0
Reputation: 7088
According to MongoDB's manual the answer is yes, it's unique by default:
MongoDB creates the _id index, which is an ascending unique index on the _id field, for all collections when the collection is created. You cannot remove the index on the _id field.
Upvotes: 3
Reputation: 95161
ok .. short version
YES
YES
YES
_id uniqid by default
, mongoDB creates index on _id
by default and you do not need any settings
Upvotes: 4
Reputation: 230541
All documents contain an _id
field. All collections (except for capped ones) automatically create unique index on _id
.
Try this:
db.system.indexes.find()
Upvotes: 14