I'm getting this error when upgrading pymongo from 3.12.1 to 4.0.1. "NotImplementedError: Database objects do not implement truth value testing or bool(). Please compare with None instead: database is not None" I'm using Python 3.9. I'm not using Django or any other package. How to solve it?
Apparently the API changed in the MongoDB client library in version 4. After getting a database or collection object (ex db_obj) from the MongoClient(...)
you can no longer use if db_obj:
and must use if db_obj is not None:
.
So this:
mongo_client = MongoClient(...)
# get a database object
db_obj = mongo_client['mydb']
if db_obj:
# get a collection
collection_obj = db_obj['my_collection']
if collection_obj:
# do a query
# ...
Must change to:
mongo_client = MongoClient(...)
# get a database object
db_obj = mongo_client['mydb']
if db_obj is not None: <-- here
# get a collection
collection_obj = db_obj['my_collection']
if collection_obj is not None: <-- here
# do a query
# ...
I had this same issue just a day after you did. It seems the old pattern still works on testing result objects from a query or insert, but you might want to update those as well in case it is deprecated in the future.