Return .str of ObjectID using pymongo

六月ゝ 毕业季﹏ 提交于 2019-12-11 14:15:21

问题


How would I return just the string component of an BSON ObjectId using pymongo. I'm able to encode a string into an Object id by importing ObjectId from bson.objectid; but am unable to do the reverse.

When I try:

for post in db.votes.find({'user_id':userQuery['_id']}):
            posts += post['_id'].str

I get an ObjectId has no attribute str error.

Thanks!


回答1:


The standard way in python to get object's string representation is using the str builtin function:

id = bson.objectid.ObjectId()
str(id)
=> '5190666674d3cc747cc12e61'



回答2:


try this:

for post in db.votes.find({'user_id':userQuery['_id']}):
            posts += str(post['_id'])

BTW, you can use MongoKit to deal with the special bson data structure.

from bson.objectid import ObjectId


class CustomObjectId(CustomType):
mongo_type = ObjectId  # optional, just for more validation
python_type = str
init_type = None  # optional, fill the first empty value

def to_bson(self, value):
    """convert type to a mongodb type"""
    return ObjectId(value)

def to_python(self, value):
    """convert type to a python type"""
    return str(value)

def validate(self, value, path):
    """OPTIONAL : useful to add a validation layer"""
    if value is not None:
        pass  # ... do something here

This custom ObjectId can turn the bson ObjectId to python str.

Visit http://mongokit.readthedocs.org/mapper.html#the-structure for more information.



来源:https://stackoverflow.com/questions/20159627/return-str-of-objectid-using-pymongo

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!