On MongoDB the _Id field for some reason is always very similar, so similar that after 20 documents I cant insert more because the _Id will be the same. What I think is happening is MongoDB generates the _Id based on what’s inside the document and all of the documents I inserted is very similar (but not the same). What I wanted to do for this is generating a random _Id to get around this.
What I tried first was randomly picking litters and numbers from a list 24 times (because the _Id field is 24 characters long), this is how I did that:
alphabet = string.ascii_letters + string.digits
key = ''.join(secrets.choice(alphabet) for i in range(24))
But that gave me a TypeError: unhashable type: 'slice'
Is there any other way to generate a random _Id?
2
Answers
The secrets.choice() function is used to select a single random element from a sequence (like a list or a string), but you’re trying to apply it to a slice (a part of a sequence). To generate a random string of a specific length using the characters from alphabet, you can modify your code like this:
Here,
for _ in range(24)
iterates 24 times, and in each iteration, a random character from alphabet is selected and added to the key string.MongoDB and its associated drivers and tools always ensure that the automatically created
_id
field is unique to the current database. For all reasonable purposes you can extend the statement to say the generated_id
s are globally unique.If you create them in quick succession they will look similar; that’s because they are made up of a random machine identifier, add the current date. crucially though there is always an incrementing 3-byte counter. So unless you are adding more than 16 million records a seconds, you won’t run into any duplicates.