Monday 9 September 2019

MongoDB update and delete records with examples

MongoDB update and delete records with examples




Question: How to Update Single Record? (Even Multiple Found)
db.players.update({"age":29},{$set:{number:1000}})
It will delete single record.
Output
WriteResult({"nMatched":1,"nUpserted":0,"nModified":1})



Question: How to update Update multiple Record? - 1 way
db.players.update({"age":29},{$set:{number:100}},{multi:true})
It will delete multiple record.
Output
WriteResult({
  "acknowledged": true,
  "matchedCount": 3,
  "modifiedCount": 3
})



Question: How to Update multiple Record? - 2 Way
db.players.updateMany({"age":29},{$set:{number:135}})
Output
WriteResult({
  "acknowledged": true,
  "matchedCount": 3,
  "modifiedCount": 3
})



Question: How to remove a Record(s)?
db.players.remove({"_id" : ObjectId("57ce95da8a12a77c41313adc")});
Will Delete all the record with matched condition.
Output
WriteResult({"nRemoved":1})



Question: How to remove a Record(s) with limit?
db.players.remove({"age":30},2);
It will deleted only 2 records.
Output
WriteResult({"nRemoved":2})