MongoDB findOneAndReplace日志,如果添加为新文档或替换为

时间:2017-09-26 17:39:37

标签: mongodb mongodb-query pymongo

我使用mongo' upsert = truereturnNewDocument = true_id

基本上是一种不插入重复的方法。但是我希望将新插入的文档(或旧的现有文档)的findOneAndReplace()传递给后台处理任务。

但我还想记录文件是否为新增或者是否发生了替换。

我无法通过这些参数找到使用find_one_and_replace()的方法并回答这个问题。

我能想到的唯一想法是找到并插入两个看起来有点适得其反的不同请求。

PS。我实际上使用的是pymongo' index,但它似乎与JS mongo函数相同。

编辑:编辑以澄清。

2 个答案:

答案 0 :(得分:1)

是否无法使用replace_one功能?在java中,我能够使用返回UpdateResult的repalceOne。这有找到记录是否更新的方法。我在pymongo看到repalce_one,它的行为应该相同。这是doc PyMongo Doc寻找replace_one

答案 1 :(得分: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