0

According to the MongoDB documentation, the _id field (if not specified) is automatically assigned a 12 byte ObjectId.

It says a unique index is created on this field on the creation of a collection, but what I want to know is how likely is it that two documents in different collections but still in the same database instance will have the same ID, if that can even happen?

I want my application to be able to retrieve a document using just the _id field without knowing which collection it is in, but if I cannot guarantee uniqueness based on the way MongoDB generates one, I may need to look for a different way of generating Id's.

Adam
  • 311
  • 1
  • 3
  • 15
  • possible duplicate of [Possibility of duplicate Mongo ObjectId's being generated in two different collections?](http://stackoverflow.com/questions/4677237/possibility-of-duplicate-mongo-objectids-being-generated-in-two-different-colle) – Christian P Jun 20 '14 at 15:47

2 Answers2

1

Short Answer for your question is : Yes that's possible.

below post on similar topic helps you in understanding better:

Possibility of duplicate Mongo ObjectId's being generated in two different collections?

Community
  • 1
  • 1
Dheeraj Palagiri
  • 1,829
  • 3
  • 23
  • 46
0
  1. You are not required to use a BSON ObjectId for the id field. You could use a hash of a timestamp and some random number or a field with extremely high cardinality (an US SSN for example) in order to make it close to impossible that two objects in the world will share the same id
  2. The _id_index requires the idto be unique per collection. Much like in an RDBMS, where two objects in two tables may very likely have the same primary key when it's an auto incremented integer.
  3. You can not retrieve a document solely by it's _id. Any driver I am aware of requires you to explicitly name the collection.

My 2 cents: The only thing you could do is to manually iterate over the existing collections and query for the _id you are looking for. Which is... ...inefficient, to put it polite. I'd rather semantically distinguish the documents in question by an additional field than by the collection they belong to. And remember, mongoDB uses dynamic schemas, so there is no reason to separate documents which semantically belong together but have a different set of fields. I'd guess there is something seriously, dramatically wrong with you schema. Please elaborate so that we can help you with that.

Markus W Mahlberg
  • 19,711
  • 6
  • 65
  • 89