简体   繁体   中英

Can mongodb “upsert” in this way?

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.

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
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM