简体   繁体   English

如何从字符串中获取 mongodb 的有效 object id?

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

I want to make my mongodb OjectId to a field:我想将我的 mongodb OjectId 设为一个字段:

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:但是有效的 ObjectId 必须是“str”类型的 12 字节输入或 24 字符的十六进制字符串,所以如果我这样做:

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

I will get an error.我会得到一个错误。 I thought a hash is a good way:我认为 hash 是个好方法:

hash("programmer") # 7354308922443094682

but as you can see, hash seems not ok.但如您所见,hash 似乎不正常。

So how can I get a valid object id?那么我怎样才能得到一个有效的 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?主要问题是因为这个字段是中文的,所以像这样: ObjectId('兼职'.decode("utf-8"))不能工作,那么我怎么才能让这个支持utf-8?

Python mongodb documentation has examples ready for you: Python mongodb文档提供了适合您的示例:

class bson.objectid.ObjectId(oid=None) 类bson.objectid.ObjectId(oid = None)

Initialize a new ObjectId. 初始化一个新的ObjectId。

ObjectId(b'foo-bar-quux')
ObjectId('666f6f2d6261722d71757578')

Is there any reason why you must generate the ObjectId from a string? 有什么理由必须从字符串生成ObjectId? If you simply wants an unique id for your mongodb document, you can generate one automatically like so 如果您只想为mongodb文档提供唯一的ID,则可以像这样自动生成一个ID

from bson.objectid import ObjectId
_id = ObjectId()

the ObjectId generated will be based on the machine's hardware signature, and the current time 生成的ObjectId将基于计算机的硬件签名以及当前时间

Assuming the string is in variable rndId , do the following:假设字符串在变量rndId中,执行以下操作:

from bson.objectid import ObjectId

rndId="1234"
collection.find_one({"_id": ObjectId(rndId)

*** Pre-install the bson package dependency: *** 预装 bson package 依赖:

> pip install bson

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM