4

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?

Ajeetkumar
  • 1,271
  • 7
  • 16
  • 34

2 Answers2

2

by default it only updates one you have to set the multi option, more info

try this:

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

Also the query is case sensitive so in your case it still would not update the second one.

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

In the second document name is starting with uppercase A. Might want to look into regex matching

Eddie Martinez
  • 13,582
  • 13
  • 81
  • 106
  • If they were both capital A it would still only update one record. If that is the issue, then he could look into matching with regex. – Eddie Martinez Apr 15 '15 at 17:47
1

{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})
Community
  • 1
  • 1
Maxim Pontyushenko
  • 2,983
  • 2
  • 25
  • 36
  • Oh I'm sorry Maxim that was a typo mistake. Name was ajeetkumar. But I get ur answer and that worked. Thanks – Ajeetkumar Apr 16 '15 at 04:34