0
我需要在mongodb中創建一個文檔,然後立即希望它在我的應用程序中可用。正常的方式做這將是(在Python代碼):MongoDB:做一個原子創建和返回操作
doc_id = collection.insert({'name':'mike', 'email':'[email protected]'})
doc = collection.find_one({'_id':doc_id})
有兩個問題:
- 兩個請求到服務器
- 不是原子
所以,我嘗試使用find_and_modify
操作來在upserts
的幫助下有效地執行「創建並返回」,如下所示:
doc = collection.find_and_modify(
# so that no doc can be found
query= { '__no_field__':'__no_value__'},
# If the <update> argument contains only field and value pairs,
# and no $set or $unset, the method REPLACES the existing document
# with the document in the <update> argument,
# except for the _id field
document= {'name':'mike', 'email':'[email protected]'},
# since the document does not exist, this will create it
upsert= True,
#this will return the updated (in our case, newly created) document
new= True
)
這確實按預期工作。我的問題是:這是否是完成「創造和回報」的正確方式,還是我缺少任何疑點?
如果我不通過_id,它是由mongo客戶端還是在服務器上創建的?因爲如果客戶端創建了_id,那麼我可能沒有從find_and_modify'中獲得任何東西。我以爲我是服務器,創建了缺少_id – treecoder
我認爲客戶端驅動程序創建_id(至少在Java中),但是它有什麼區別是誰做的? – Thilo
可能不是。我只是有點擔心我自己插入的文檔與數據庫返回的完全一樣,並且從數據庫中獲得原始副本感覺更舒適一些。但我想你是對的。 – treecoder