I want to insert document to the collection from json file it says bson.errors.InvalidDocument: key '$oid' must not start with '$'
How can I solve it?
example of document:
[{"name": "Company", "_id": {"$oid": "1234as123541gsdg"}, "info": {"email": "[email protected]"}}]
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.
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