Ad

Is There A Way To Create An ObjectID From INT In MongoDB?

- 1 answer

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.

Ad

Answer

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
Ad
source: stackoverflow.com
Ad