Domanda

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.

È stato utile?

Soluzione

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
)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top