Question

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!

Was it helpful?

Solution

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

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top