首页 文章

使用pymongo返回ObjectID的.str

提问于
浏览
0

我如何使用pymongo返回BSON ObjectId的字符串组件 . 我可以通过从bson.objectid导入ObjectId将字符串编码为Object id;但我无法做到相反 .

当我尝试:

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

我得到一个ObjectId没有属性str错误 .

谢谢!

2 回答

  • 2

    python中获取对象字符串表示的标准方法是使用 str 内置函数:

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

    试试这个:

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

    顺便说一句,您可以使用MongoKit来处理特殊的bson数据结构 .

    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
    

    这个自定义ObjectId可以将bson ObjectId 变为python str .

    有关更多信息,请访问http://mongokit.readthedocs.org/mapper.html#the-structure .

相关问题