问题
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