Search code examples
pythonmysqlbson

May I use bson.objectid.ObjectId as (primary key) id in sql?


I am thinking if I don't use auto id as primary id in mysql but use other method to implement, may I replace auto id from bson.objectid.ObjectId in mysql?

According to ObjectId description, it's composed of:

  • a 4-byte value representing the seconds since the Unix epoch
  • a 3-byte machine identifier
  • a 2-byte process id
  • a 3-byte counter, starting with a random value.

It seems it can provide unique and not duplicate key. Is it a good idea?


Solution

  • You certainly could do this. One issue though is that since this can't be set by the database itself, you'll need to write some Python code to ensure it is set on save.

    Since you're not using MongoDB, though, I wonder why you want to use a BSON id. Instead you might want to consider using UUID, which can indeed be set automatically by the db.