Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask PyMongo string back to ObjectID [duplicate]

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'>
like image 494
Max Powers Avatar asked Oct 15 '17 05:10

Max Powers


1 Answers

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.

like image 145
tfogo Avatar answered Sep 28 '22 16:09

tfogo