Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bson.errors.InvalidDocument: key '$oid' must not start with '$' trying to insert document with pymongo

Tags:

python

pymongo

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]"}}]

like image 360
Vadim Kovrizhkin Avatar asked Feb 07 '17 11:02

Vadim Kovrizhkin


1 Answers

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.

like image 108
A. Jesse Jiryu Davis Avatar answered Oct 17 '22 16:10

A. Jesse Jiryu Davis