This question has originally been asked in dba.stackexchange.com. I'm trying to migrate user ids from MySQL to MongoDB and I want to create objectIDs from an int. Is there a way to store INTs inside of ObjectID parts like the random section of ObjectID? Then convert it back to from ObjectID to int.
Asked
Active
Viewed 1,856 times
1 Answers
3
Ok, there is straightforward approach:
import bson
def object_id_from_int(n):
s = str(n)
s = '0' * (24 - len(s)) + s
return bson.ObjectId(s)
def int_from_object_id(obj):
return int(str(obj))
n = 12345
obj = object_id_from_int(n)
n = int_from_object_id(obj)
print(repr(obj)) # ObjectId('000000000000000000012345')
print(n) # 12345

sanyassh
- 8,100
- 13
- 36
- 70