2

I want to check that if I use _id fields that refer to documents from different collections, I will never have a duplicate _id, i.e. used in 2 different collections inside the same database.

Using meteor (so both in minimongo and mongodb), is the _id field unique in its collection or in the entire database?

Billybobbonnet
  • 3,156
  • 4
  • 23
  • 49

1 Answers1

3

The _id values you have in your database are generated by Meteor using Random.id(). These are unique across all collections.

Please note that the uniqueness of _id values in MonogoDB is ensured on the collection level, meaning that there is always a unique index on the _id field for every collection. There is no MongoDB mechanism in place that would ensure _id uniqueness across collections.

In any case, it is quite a safe assumption that Meteor's random IDs will never collide.

Dmytro Shevchenko
  • 33,431
  • 6
  • 51
  • 67
  • 1
    As you said, this is a "safe assumption". But, still, that's an assumption. Are they guaranteed to be unique, or not (suppose I have millions and millions of documents and resources are not an issue)? I mean, is there a mechanism in place where if the Random.id() was already generated before that it will be skipped and a new one generated? Because, if not, then there *can* be collisions (even if they are unlikely, but, people have been known to win the lottery). – trusktr Feb 20 '16 at 21:21
  • How can we make sure that the id Meteor generates would not collide with existing ones on a collection? (Throwing an error is not ok cause it would break the operation and prevent the data from being saved) – cenk Feb 25 '17 at 00:42