1

I am trying to get the auto-generated ID from the DocumentReference Object

DocumentReference docref = db.collection("users").document(); 
String ID = check.getID();

The question is since the ID's are generated at client side there can be chances that 2 ID in firestore are similar to each other when their are more than a million document in a collection and when I use .set() the document gets updated. I have seen other answer but none solved my doubt.

  • Check also **[this](https://stackoverflow.com/questions/53119133/firestore-generated-unique-ids-for-more-then-1-collection)** out. – Alex Mamo Apr 11 '20 at 10:29

1 Answers1

2

At the time of writing, a Firestore Auto ID (at least in the JavaScript SDK) is constructed from 20 random characters selected from the characters a-z, A-Z and 0-9 - so 20 characters chosen from 62 possible characters.

This means that there are 62^20 (or 7.01e35) different possible combinations.

This is very similar to the 2^120 possible combinations used in the Realtime Database (that also use the - and _ characters for 64^20 possible combinations).

The main difference between RTDB's Push IDs and Firestore's Auto IDs is that the auto ids are not encoded according to the device timestamp - all ~120 bits are random.

So, statistically it is very unlikely that you will encounter a collision. But you can always use your own system to generate your own IDs or use some drop in uuid package to generate a 128-bit or greater ID.

samthecodingman
  • 23,122
  • 4
  • 30
  • 54
  • 3
    You would have to generate 1.3 quintillion auto ids to have a 50% probability of a collision. You'd have to generate 163 quadrillion auto ids to have 1% probability of a collision. – samthecodingman Apr 10 '20 at 18:39
  • Not only javascript any programming language – Peter Haddad Apr 10 '20 at 18:48
  • To build on @samthecodingman 's answer with a relatable number, to have a 1% probability of collision, you'd need (one million x one billion = one quadrillion) documents in the same collection. So if you have a chat app where each chat is a document in a collection, and there are 1 billion chats, you'd need to multiply the number of chats by 1 million to get a 1% chance of collision. – Matthew Rideout Dec 22 '22 at 21:31