我使用的是Django + mongoengine我想更新Bookscollection文档中的图书(嵌入文档)计数。我希望更新查询返回完整对象。因此,我使用'find_and_modify'。但即使我使用update或remove字段。我仍然得到一个错误,"必须更新或删除"。这是我的代码片段-
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
})
怎么了?
find_and_modify
接受一个关键字参数,这就是为什么你得到这个错误消息。
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
})
你也应该知道find_and_modify
在pymongo3.0中是不赞成的,如果你的潜水员是pymongo 2.9或更新的,你应该使用find_one_and_update
。
BookCollection._get_collection().find_and_modify(
query={'coll_id':book_coll_id,'book.book_id': book_id},
update={'$inc': {'book.$.quantity' : 1}},
new=True
)
对于pymongo 3.0之后的任何人,您需要使用.find_one_and_update
而不是find_and_modify
,因为它已被弃用。
的例子:
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
)