2013-03-28 29 views
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 
) 

這確實按預期工作。我的問題是:這是否是完成「創造和回報」的正確方式,還是我缺少任何疑點?

回答

1

你從簡單的舊的普通插入呼叫中錯過了什麼?

如果它不知道_id是什麼,那麼您可以先自己創建_id並插入文檔。那麼你確切知道它會是什麼樣子。其他字段都不會與您發送到數據庫的字段不同。

如果您擔心插入操作已成功,您可以檢查返回碼,並設置一個write concern以提供足夠的保證(例如已刷新到磁盤或複製到足夠的節點)。

+0

如果我不通過_id,它是由mongo客戶端還是在服務器上創建的?因爲如果客戶端創建了_id,那麼我可能沒有從find_and_modify'中獲得任何東西。我以爲我是服務器,創建了缺少_id – treecoder

+0

我認爲客戶端驅動程序創建_id(至少在Java中),但是它有什麼區別是誰做的? – Thilo

+0

可能不是。我只是有點擔心我自己插入的文檔與數據庫返回的完全一樣,並且從數據庫中獲得原始副本感覺更舒適一些。但我想你是對的。 – treecoder