2017-09-26 36 views
0

我使用蒙戈的findOneAndReplace()upsert = truereturnNewDocument = trueMongoDB的findOneAndReplace日誌作爲新的文檔或更換

爲基本方式不重複插入。但我想要將新插入文檔(或舊的現有文檔)的_id傳遞給後臺處理任務。

但我也想記錄,如果該文件是新增或新的,或如果更換髮生。

我看不到任何方式使用這些參數findOneAndReplace()並回答該問題。

唯一能想到的就是找到並插入兩個不同的請求,這似乎有點反作用。

ps。我實際上使用pymongo的find_one_and_replace(),但它似乎與JS mongo函數相同。

編輯:編輯澄清。

+0

與返回新文件你沒有得到被替換的文件?您應該能夠從替換的文檔中獲取_id。可能是我不理解這個問題? – JavaProgrammer12

+0

我需要記錄文檔是否爲新增或者是否有替換髮生。我正在使用findOneAndReplace,因爲我的添加腳本變成了idempotetent,但我仍然對添加的新事物感到好奇。 – mtourne

回答

1

是沒可能使用replace_one功能?在Java中,我能夠使用返回UpdateResult的repalceOne。該方法可以查找是否更新了文檔。我在pymongo中看到repalce_one,它應該表現相同。這裏是文檔PyMongo Doc尋找replace_one

0

我要去實現它現在的方式(在python):

import pymongo 

def find_one_and_replace_log(collection, find_query, 
          document_data, 
          log={}): 
    ''' behaves like find_one_or_replace(upsert=True, 
    return_document=pymongo.ReturnDocument.AFTER) 
    ''' 
    is_new = False 
    document = collection.find_one(find_query) 
    if not document: 
     # document didn't exist 
     # log as NEW 
     is_new = True 
    new_or_replaced_document = collection.find_one_and_replace(
     find_query, 
     document_data, 
     upsert=True, 
     return_document=pymongo.ReturnDocument.AFTER 
    ) 
    log['new_document'] = is_new 
    return new_or_replaced_document