Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pymongo's update_one() returns UpdateResult with AttributeError

I just upgraded my MongoDB and Pymongo to the latest version 3.2.1 to be able to use the UpdateResult object after calling update_one(). But for some reason the returned object has one field that contains an AttributeError.

Take a look at my Pycharm screen. You can see that _UpdateResult__acknowledged

'Traceback (most recent call last):
  File "/opt/pycharm-community-5.0.4/helpers/pydev/pydevd_resolver.py", line 191, in _getPyDictionary
    attr = getattr(var, n)
AttributeError: _UpdateResult__acknowledged'

It causes me a problem since I am trying to catch all exceptions and every time I need to use update_one() in my code I get this exception.

This is a snippet of my code:

QUERY = {id: '1234'}
try:
    record = mongoCollection.find_one(QUERY)
    if record is None:
        print 'Add new Record'
    else:
        updateResult = mongoCollection.update_one(
            QUERY,
            {'$addToSet': {'info': getInfo()}}
        )

        if updateResult['modified_count'] == 1:
            mongoCollection.update_one(
                QUERY,
                {'$inc': {'infoCount': 1}}
            )
        print 'Record exists, updating if needed'
except:
    print 'Failed to add/update'

Luckily I was able to find a workaround that doesn't cause this exception to be raised. Instead of using update_one(), I can use the deprecated function update() which returns only the RAW result from MongoDB and then instead of comparing updateResult['modified_count'], I can just compare updateResult['nModified'].

But this is definitely not a best practice to use deprecated functions... :(

Any thoughts?

like image 708
BeePi Avatar asked Feb 10 '16 12:02

BeePi


1 Answers

For those who may encounter the same error, I was able to get an answer here: https://jira.mongodb.org/browse/PYTHON-1055

In short, since UpdateResult is not a python dictionary and doesn't implement __getitem__. The problem was trying to do

 updateResult['modified_count'] == 1

instead I should have used

 updateResult.modified_count == 1

because UpdateResult.modified_count is a property.

like image 173
BeePi Avatar answered Sep 18 '22 01:09

BeePi