how can I get a valid object id of mongodb from a string?

13,124

Solution 1

Is there any reason why you must generate the ObjectId from a string? If you simply wants an unique id for your mongodb document, you can generate one automatically like so

from bson.objectid import ObjectId
_id = ObjectId()

the ObjectId generated will be based on the machine's hardware signature, and the current time

Solution 2

Python mongodb documentation has examples ready for you:

class bson.objectid.ObjectId(oid=None)

Initialize a new ObjectId.

ObjectId(b'foo-bar-quux')
ObjectId('666f6f2d6261722d71757578')
Share:
13,124

Related videos on Youtube

roger
Author by

roger

Updated on June 04, 2022

Comments

  • roger
    roger almost 2 years

    I want to make my mongodb OjectId to a field:

    class ZhinengStats(Document):
        zhineng_id = ObjectIdField(db_field="_id", primary_key=True, required=True, help_text="job id")
    

    but a valid ObjectId must be a 12-byte input of type 'str' or a 24-character hex string, so if I do this:

    ZhinengStats.objects(zhineng_id="programmer").first()
    

    I will get an error. I thought a hash is a good way:

    hash("programmer") # 7354308922443094682
    

    but as you can see, hash seems not ok.

    So how can I get a valid object id?


    UPDATE:

    the main problem is because this is field is a chinese, so something like this:ObjectId('兼职'.decode("utf-8")) can not work, so how can I make this support utf-8?

    • Sylvain Leroux
      Sylvain Leroux almost 9 years
      Python 2 or Python 3 ?
    • roger
      roger almost 9 years
      @SylvainLeroux python 2
    • Bacar Pereira
      Bacar Pereira about 3 years
      Check this link will help you stackoverflow.com/a/66117385/9416032
  • roger
    roger almost 9 years
    I have a problem with this, chinese is not ok, such as ObjectId(u"兼职") returns bson.errors.InvalidId: u'\u517c\u804c' is not a valid ObjectId, it must be a 12-byte input of type 'str' or a 24-character hex string
  • Salvador Dali
    Salvador Dali almost 9 years
    @roger may be this will help: stackoverflow.com/questions/24571790/…
  • roger
    roger almost 9 years
    you mean ObjectId("兼职".decode("utf-8"))? this can not work.