[英]Pymongo: Identify if document returned by find_one_and_update is updated or inserted
我想知道find_one_and_update
返回的文檔是新的(插入的)還是更新的。
我的查詢如下:
predicted_user = db.predictions.find_one_and_update({'emp_name': user_name},
{'$currentDate': {"createdAt": True}},
upsert=True,
return_document=ReturnDocument.AFTER)
Forecast_user可以是:
upsert
,該集合中有一個新用戶。 update
命令,其createdAt
已被更新的舊用戶。 我想實現類似
if predicted_user is new:
# Do send notifications.
else:
# Don't send notifications.
以上可以通過多個查詢來實現,但是我想將其保持為單個(如果可能)。
您將需要實現文檔版本控制。 例如,如果您將文檔版本保留在_version
字段中,則update參數可以是:
{
'$currentDate': { "createdAt": True },
'$inc': { '_version': 1 },
'$setOnInsert': { '_version': 0 }
}
然后,您可以檢查_version的值。 升級后的文檔將為0,更新后的文檔將為0。
您將需要更新現有文檔以在部署期間手動添加字段:
{'$set': { '_version': 1 }}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.