Search code examples
mongodbflaskpymongopymongo-3.xflask-pymongo

Flask PyMongo string back to ObjectID


I am using flask with pymongo and I have a case where my Object Id is being converted into a string. How can I change it back to an Object Id so I can use if for querying ?

From : 59d7ef576cab3d6118805a20
type is <class 'str'>

To: ObjectId("59d7ef576cab3d6118805a20")
type is <class 'bson.objectid.ObjectId'>

Solution

  • You can use bson.objectid.ObjectId to create an ObjectId from a string. See the docs for this on the pymongo site: http://api.mongodb.com/python/current/api/bson/objectid.html

    For example:

    from pymongo import MongoClient
    from bson.objectid import ObjectId
    
    client = MongoClient()
    collection = client.test.test
    
    print(collection.find_one({"_id": ObjectId("59d7ef576cab3d6118805a20")}))
    

    The bson package is installed with pymongo. You don't need to install a separate bson package.