3

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": "test@gmail.com"}}]

  • Could you give example document? It seems that you have value of the document id starting with "$" – Tomasz Swider Feb 7 '17 at 11:46
  • You're most likely going to need to escape that $. A simple way is: import re; re.escape({your variable here}) – Nether Feb 7 '17 at 11:49
  • I have updated the question body with example of document – Vadim Kovrizhkin Feb 7 '17 at 11:50
  • What is wrong with "_id": "1234as123541gsdg"? – styvane Feb 7 '17 at 11:54
  • I get it when I dump the collection to json file – Vadim Kovrizhkin Feb 7 '17 at 11:55
8

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": "test@gmail.com"}})

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": "test@gmail.com"}}]'

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.

| improve this answer | |
  • You're welcome! Is there anything else I should add to my answer, or will you mark it as correct? – A. Jesse Jiryu Davis Feb 8 '17 at 12:15
  • Anyone knows if there is something similar for Ruby? – everyman Oct 5 '18 at 9:50
  • Just wanted to spell it out that you can get the json_str from the json file with file.read(). open("filepath", "r") as f: json_str = f.read() – mirthbottle Jul 22 at 16:24
  • did it worked?? – Navi Sep 18 at 10:16
0

Try removing all white space in the files (\n, spaces outside string quotes). It may work like miracle

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.