0

I know that in conventional upsert operation of mongodb, if a document exists, mongodb will perform update, otherwise it will do insert. However what I want is: if a document exists, mongodb just leave it unchanged, otherwise it will do insert. Of course it can be implemented with conventional upsert by using the same data to update the old document. But the thing is: the update operation is totally unnecessary; the mongodb can just skip it. Of course I can also use the read-test-write statements to do this job, but I'm restricted to python, and therefore this approach is computationally expensive. So I post the thread here asking if mongodb has any operation that runs as fast as "upsert" by skipping any existing documents if any, and inserting a new document otherwise. Thank you.

4

1 回答 1

3

upsert的$setOnInsert参数仅在插入时设置字段,而不是在更新时设置字段。当您没有其他更新参数或字段时,现有文档根本不会受到此查询的影响。

你可以这样使用它:

db.collection.update(
    { 
        <your query >
    },
    { $setOnInsert: {
             <your new document>
        }
    },
    true //upsert
)
于 2013-11-13T12:04:42.430 回答