'Mongoengine raw find_and_modify query gives "Must either update or remove" exception

I am using Django + mongoengine I want to update the books (embedded document) count in my Bookscollection document. I want the update query to return the full object. Therefore I am using the 'find_and_modify'. But even if I use update or remove fields. I still get an error that 'Must either update or remove'. Here is my code snippet -

for book_id in book_list:
        book_col = BookCollection._get_collection().find_and_modify({
                        'query': {'coll_id':book_coll_id,'book.book_id':book_id},
                        'update':{'$inc':
                             {'book.$.quantity' : 1}
                         },
                        'new':True
        })

What is wrong here?



Solution 1:[1]

find_and_modify takes a keywords arguments that is why you are getting that error message.

for book_id in book_list:
    book_col = BookCollection._get_collection().find_and_modify({
                        query={'coll_id':book_coll_id,'book.book_id': book_id},
                        update={'$inc': {'book.$.quantity' : 1}},
                        new=True
                })

Also you should know that find_and_modify is deprecated in pymongo3.0 you should use the find_one_and_update if your diver is pymongo 2.9 or newer.

Solution 2:[2]

BookCollection._get_collection().find_and_modify(
                    query={'coll_id':book_coll_id,'book.book_id': book_id},
                    update={'$inc': {'book.$.quantity' : 1}},
                    new=True
            )

Solution 3:[3]

For anyone coming here after pymongo 3.0, you need to use .find_one_and_update instead of find_and_modify since it is deprecated.

example:

book_col = BookCollection._get_collection().find_one_and_update(
                filter={'coll_id':book_coll_id,'book.book_id': book_id},
                update={'$inc': {'book.$.quantity' : 1}},
                new=True
        )

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 styvane
Solution 2 Jibin Mathew
Solution 3 omercotkd