[Django]-Mongoengine raw find_and_modify query gives "Must either update or remove" exception

2👍

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.

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
            )

0👍

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
        )

Leave a comment