Search code examples
djangomongodbpymongomongoengine

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

  • 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.