72

Can Mongo IDs have the same value in different collections in the same database?

B Seven
  • 44,484
  • 66
  • 240
  • 385
CamelCamelCamel
  • 5,200
  • 8
  • 61
  • 93
  • It might help http://www.code-sample.com/2016/07/are-mongodb-ids-unique.html – Anil Singh Jul 18 '16 at 05:30
  • 2
    Does this answer your question? [Possibility of duplicate Mongo ObjectId's being generated in two different collections?](https://stackoverflow.com/questions/4677237/possibility-of-duplicate-mongo-objectids-being-generated-in-two-different-colle) – Robin Jan 14 '20 at 10:23

1 Answers1

78

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.

svjson
  • 2,085
  • 19
  • 13
  • 16
    how unlikely is it? Should I code with the assumption that this will never happen to me unless I insert duplicates manually? – CamelCamelCamel Mar 14 '11 at 20:18
  • 2
    Yes, it is very unlikely since it is a guid. You should not accidentally be able to hit a collision very easily. – Scott Hernandez Mar 14 '11 at 20:54
  • 14
    Check out the MongoDB docs on the ObjectID to learn more about why its seemingly impossible: http://www.mongodb.org/display/DOCS/Object+IDs#ObjectIDs-BSONObjectIDSpecification – Bryan Migliorisi Mar 15 '11 at 02:52
  • It is almost impossible but the problem lies in the drivers generating their own ObjectIds. So basically you can have two clients generating the same id but its quite unlikely and depends on the driver implementation. – Martin Kersten Mar 29 '14 at 13:18
  • 1
    Here's good document about the uniqueness of ObjectIDs and other alternatives in case the default one doesn't suit you : https://www.mongodb.com/blog/post/generating-globally-unique-identifiers-for-use-with-mongodb – Kamagatos Jan 13 '20 at 09:07