Search code examples
mongodbupdating

mongodb not updating all the documents


I have documents {name:"ajeetkumar",age:26} and {age:26,name:"ajeetkumar"} stored in collection sample.

I want to update the age field and i use command db.sample.update({name:"ajeetkumar"},{$set:{age:28}})

It only updates the first document where name is the first field. Why? How to update all the records given a field. Is order of fields affecting the update?


Solution

  • {name:"ajeetkumar",age:26} and {age:26,name:"Ajeetkumar"}

    db.sample.update({name:"ajeetkumar"},{$set:{age:28}})

    In the second document name is starting with uppercase A so you should use regex in this one. Plus you have to use multi option. This one will work well for you:

    db.sample.update({name: /^ajeetkumar/i},{$set:{age:28}}, {multi: true})