[00:00] Sometimes we would like to perform an update or a replacement, but we don't know whether a document exists at all. So first we would have to check the existence and only then conditionally perform the update. Now this could be slightly troublesome since there might be multiple calls to the database and we would like to perform it in one shot. And this is called upsert. Now in a Mongo collection API there is no operation that is called upsert.
[00:27] However, we can do it using either update or replace. So first of all let's try to update a document that does not exist and for this reason let's try to update a document that has a name kill bill and let's also figure out that there would be a skill that the document would have and that would be a kaboom. Now the update that we want to do here is let's say that would be a set and we want to set that there would be age 40 or whatever and if we run this command we would see that there is acknowledged true because it's syntactically correct etc but nothing has been matched, nothing has been inserted, nothing has been modified or upserted. By the way this is the one that we're interested in. Now using update1 what we can do is to pass another property that is going to be the flag that is upsert which is true.
[01:29] So if this one doesn't exist, please create it. So what we've got right here is that there would be Kill Bill, Skills and Age presented. And as we can see, acknowledge true inserted IDs. Here comes the one that was inserted but also it was not only inserted but actually also upserted. So these two define this operation.
[01:52] Now if we run db.employees.find, then we would see the very last document, which is the one that we're interested in. Now let's also run a very similar thing using the replaceOne method. Now we're going to, again, update something that does not exist. So that would be a document which includes a Jane Smith name. And what we want to replace it with is going to be a name which is Judy Smith.
[02:22] Now if we execute this command we would see that there is basically nothing going on because there was no document that has been matched. However if we pass the third argument which is going to be a set of options and we define the absurd true then we would see that yes there is an inserted document and one of them has been absurded. Now if we run the db.find we would see that this is the document that has been absurded.