Pymongo bug: UpdateResult.did_upsert throws

I’m using pymongo 4.9.1 with a local, docker-deployed atlas install of MongoDB 7.0.12.

MRE:

from pymongo import MongoClient

mc = MongoClient(directConnection=True)

# Record to be upserted just needs to not already exist
update_result = mc.mydatabase.mycollection.update_one(
    {"hi": 55, "ok": 10},
    {"$set": {"well": 55}},
    upsert=True,
)

update_result.did_upsert

Evaluating did_upsert throws because:

python3.10/site-packages/pymongo/results.py", line 176, in did_upsert
      return len(self.__raw_result.get("upserted", {})) > 0
  TypeError: object of type 'ObjectId' has no len()

As the error implies, self.__raw_result["upserted"] is a bson.objectid.ObjectId.

Seems like a very straightforward bug to me. Let me know if you need any more information.

I created a ticket to track this here: https://jira.mongodb.org/browse/PYTHON-4786

did_upsert was added accidentally and was never intended to be included in the 4.9 release. Instead, to check for an upsert an app can use this existing api:

did_upsert = update_result.upserted_id is not None
1 Like