We can use update() method to update a collection in MongoDB.
Basic syntax will be like this:
db.<Collection Name>.update().
To update() method, we need to pass the data selection criteria and what we need to update in the selected data.
I have a below collection and data.
I want to update student name who is having ID 100 in the above collection. To do this, I have to execute below query.
We can upsert data as well into collection (Upsert definition: If data exists for the selection criteria then data will be updated otherwise, data will be inserted as new document into collection)
To upsert data, we need to pass "upsert":true option to the update() method.
In the below example, i am trying to upsert record with Student Id 102. But this 102 does not exist so it should insert as new record.
update() will update only first record by default. To update multiple records, we need to pass "true" value for "multi" key in update query.
Let's assume i have multiple records with the Student ID 105. I want to update all the records. This query will do that.
In the above data, the status is "active" for the records with ID 105. Now, am going to update those with "Inactive" using below query.
Here, $set used to set the value for only the mentioned field.
Basic syntax will be like this:
db.<Collection Name>.update().
To update() method, we need to pass the data selection criteria and what we need to update in the selected data.
I have a below collection and data.
I want to update student name who is having ID 100 in the above collection. To do this, I have to execute below query.
We can upsert data as well into collection (Upsert definition: If data exists for the selection criteria then data will be updated otherwise, data will be inserted as new document into collection)
To upsert data, we need to pass "upsert":true option to the update() method.
In the below example, i am trying to upsert record with Student Id 102. But this 102 does not exist so it should insert as new record.
update() will update only first record by default. To update multiple records, we need to pass "true" value for "multi" key in update query.
Let's assume i have multiple records with the Student ID 105. I want to update all the records. This query will do that.
In the above data, the status is "active" for the records with ID 105. Now, am going to update those with "Inactive" using below query.
Here, $set used to set the value for only the mentioned field.
Very helpful..detail explanation
ReplyDelete