0
votes

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.

1
As far as I know, there is no way to do it without doing read test. Don't think MongoDB has any options to do this.Deniz Zoeteman
If so, then rewrite with the same data using upsert may be the only way out.user2384994

1 Answers

3
votes

There is the $setOnInsert parameter for upsert's which only sets fields on an insert, not when on an update. When you have no other update parameters or fields, existing documents won't be affected at all by this query.

You can use it like that:

db.collection.update(
    { 
        <your query >
    },
    { $setOnInsert: {
             <your new document>
        }
    },
    true //upsert
)