Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - bson import error after upgrading to 3.9.1

Tags:

python

I have a script that I wrote under an earlier version of python (3.8).

The script blows up with a stack trace when I run it now:

python .\ec2_mongo.py
Traceback (most recent call last):
  File "C:\Users\tdun0002\OneDrive - Synchronoss Technologies\Desktop\important_folders\Jokefire\git\jf_cloud_scripts\aws_scripts\python\aws_tools\ec2_mongo.py", line 11, in <module>
    from pymongo import MongoClient, errors
  File "C:\Users\tdun0002\OneDrive - Synchronoss Technologies\Desktop\important_folders\Jokefire\git\jf_cloud_scripts\aws_scripts\python\aws_tools\venv\lib\site-packages\pymongo\__init__.py", line 87, in <module>
    from pymongo.collection import ReturnDocument
  File "C:\Users\tdun0002\OneDrive - Synchronoss Technologies\Desktop\important_folders\Jokefire\git\jf_cloud_scripts\aws_scripts\python\aws_tools\venv\lib\site-packages\pymongo\collection.py", line 20, in <module>
    from bson.code import Code
  File "C:\Users\tdun0002\OneDrive - Synchronoss Technologies\Desktop\important_folders\Jokefire\git\jf_cloud_scripts\aws_scripts\python\aws_tools\venv\lib\site-packages\bson\code.py", line 18, in <module>
    from bson.py3compat import abc, string_type, PY3, text_type
ImportError: cannot import name 'abc' from 'bson.py3compat'

In my code I am only using ObjectId from the bson package. So this is my import line:

from bson.objectid import ObjectId

My code that uses ObjectId from the bson package looks like this:

def insert_doc(mydict):
    _, _, instance_col = set_db()
    mydict["_id"] = ObjectId()
    instance_doc = instance_col.insert_one(mydict)
    if __name__ == "__main__":
        message = "* MongoDB Insert Document *"
        banner(message, "*")
        message = f"MongoDB record inserted: {instance_doc.inserted_id}"
        banner(message)
    return instance_doc

I don't know why this works under 3.8 but I get a stacktrace under 3.9.1. How can i get this working under the newer version?

like image 544
bluethundr Avatar asked Oct 19 '25 14:10

bluethundr


1 Answers

This is likely due to version mismatches.

Try doing:

pip uninstall bson
pip uninstall pymongo
pip install pymongo
like image 107
Synthase Avatar answered Oct 22 '25 05:10

Synthase



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!