5

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

5
  • Could you give example document? It seems that you have value of the document id starting with "$" Feb 7, 2017 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, 2017 at 11:49
  • I have updated the question body with example of document Feb 7, 2017 at 11:50
  • What is wrong with "_id": "1234as123541gsdg"?
    – styvane
    Feb 7, 2017 at 11:54
  • I get it when I dump the collection to json file Feb 7, 2017 at 11:55

2 Answers 2

9

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.

4
  • You're welcome! Is there anything else I should add to my answer, or will you mark it as correct? Feb 8, 2017 at 12:15
  • Anyone knows if there is something similar for Ruby?
    – everyman
    Oct 5, 2018 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() Jul 22, 2020 at 16:24
  • Is there a similar library for node? Oct 27, 2022 at 10:14
-1

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

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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