Represent ObjectIds in Python with the bson.ObjectId
class:
from bson import ObjectId
_id = ObjectId("5899e0aca600741755433908")
So for a complete example:
from bson import ObjectId
collection.insert(
{"name": "Company", "_id": ObjectId("5899e0aca600741755433908"),
"info": {"email": "[email protected]"}})
In order to load MongoDB Extended JSON data, use PyMongo's json_util.loads
:
from bson.json_util import loads
json_str = '[{"name": "Company", "_id": {"$oid": "5899e0aca600741755433908"}, "info": {"email": "[email protected]"}}]'
data = loads(json_str)
print(data)
for doc in data:
collection.insert(doc)
"loads()" converts from the Extended JSON syntax with "$oid" to an actual ObjectId instance.
$
. A simple way is:import re; re.escape({your variable here})
"_id": "1234as123541gsdg"
?