MongoDB tutorials
5. Update, increment, and delete documents
Video tutorial:
You can update the document in MongoDB collection using update() function. First parameter will be the query to find the document and second parameter will be the value to update the document.
db.users.update({ "name": "Ali" }, { $set: { "age": 30 } })
This will search for document having name “Ali” and update it’s age value to 30. Make sure you are using $set operator, otherwise it will remove all the other fields. $set operator will make sure that only those fields will be updated, other fields will remain unchanged.
Now in order to increment or decrement the integer value, you can use $inc and $dec operator:
db.users.update({ "name": "Ali" }, { $inc: { "age": 3 } })
This will increment the age value by 3 of document having name “Ali”. And same goes for $dec, I would prefer that you should try that on your own. If you got any error, feel free to ask in the comments section below. Now in order to delete any document from MongoDB collection, you can use remove() function and pass in the object as a parameter:
db.users.remove({ "name": "Ali" })
This will remove the documents having the name “Ali”. If you want to delete only 1 document, you should use deleteOne function. The parameter remains the same.