2013-11-23 27 views
0

如何僅使用pymongo返回BSON ObjectId的字符串組件。我可以通過從bson.objectid導入ObjectId將字符串編碼到Object id中;但我無法做到相反。使用pymongo返回ObjectID的.str

當我嘗試:

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

我得到的ObjectId有沒有屬性海峽錯誤。

謝謝!

回答

2

在Python標準的方式來獲得對象的字符串表示使用str內置函數:

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

謝謝! - 看起來真的很明顯現在:( –

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