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'>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With