Problem in working with updateOne and upserts together

how i have to create" detail" document so that it works because right now when i was running the query having updateOne and upserts so “detail is not his defined” so what should i do so that to remove this error.

Hi @Akash_06246,

The movieDetails collection is to be loaded into the sandbox cluster - you can find the zip file for the same in handouts section. Please try loading the file and then run your query from your sandbox cluster, it should work fine.

Please get back in case you still face any issues with it.

Thanks,
Muskan
Curriculum Support Engineer

1 Like

i was running the query for upserts as mentioned in lecture but it not executed successfully and its showing that “detail” is not defined so what should i do to make detail defined.

Hi @Akash_06246,

Please share the screenshot of the commands that you are running.
You will have to create the detail object first and then you can run the db.movieDetails.updateOne() command. Please consider the example as below:

let detail = {..document containing imdb.id..}

Here, detail variable should contain document and then updateOne() will check if imdb id exists in the collection. If it exists, then the document will be replaced with the same document else upsert will be performed to create a new document in the collection using the following command:

db.collection.updateOne({
   "imdb.id": detail.imdb.id
}, {
   $set: detail
}, {
     upsert: true,
   }
) 

Please let me know, if you have any questions.

Thanks,
Sonali

Hi @Sonali_Mamgain,

For the case where the document exists and it get replaced with the same document? Does an actual disk write take place? If yes then isn’t it an overhead?

Thanks,
Manu

Hi @Manu_07553,

[Edit : ] If it exists, then the updateOne() will perform an update on the matched document

Let’s see the behaviour of the updateOne() function with {upserts : true}. There are two possible cases here.

  1. The selection criteria for the update matches any document.

In this case, the updateOne() will perform the required updates in the same document. It could be either addition of a field, removal of an existing field, modification of an existing field or any other valid update operation.

  1. The selection criteria for the update does not match any document

In this case, upsert operation will be performed and a new document will be inserted in the collection.

Hope it helps. If you still have any query, please feel free to get back to us.

Happy Learning :slight_smile:

Thanks,
Shubham Rajan
Curriculum Support Engineer