【问题标题】:Return .str of ObjectID using pymongo使用 pymongo 返回 ObjectID 的 .str
【发布时间】:2013-12-08 04:55:06
【问题描述】:

如何使用 pymongo 仅返回 BSON ObjectId 的字符串组件。我可以通过从 bson.objectid 导入 ObjectId 将字符串编码为 Object id;但我无法反其道而行之。

当我尝试时:

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

我得到一个 ObjectId has no attribute str 错误。

谢谢!

【问题讨论】:

    标签: pymongo bson


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢! - 现在看起来真的很明显:(
    【解决方案2】:

    试试这个:

    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了解更多信息。

    【讨论】:

      猜你喜欢
      • 2018-03-26
      • 2017-02-03
      • 2013-08-08
      • 1970-01-01
      • 2015-05-08
      • 2013-04-11
      • 1970-01-01
      相关资源
      最近更新 更多